Basically, I want to use the Array type struct in the types
module but I'm unable to initialize it. What do you have to pass in the Type as the first argument?
package main
import (
"fmt"
"go/types"
)
func main() {
var a *types.Array
a = types.NewArray(types.Int, 2) //error here
fmt.Println(a)
}
I'm also new in go. And for me the question doesn't look stupid. Unfortunately no one has explained how to use NewArray yet. It seems to me that golang community is not very friendly I've met more downvoting than real help for now.
Btw I took course of Go tour :) But anyway I was confused that question how to get type of an object bring you to reflect package
usually (type in google something like golang get type of an object
) which has nothing in common with types.Type
. I spent some time to figure out how to get types.Type
object, and it's not obvious I think for people who has experience in other languages.
So to use NewArray
method you neeed to pass an object which implements types.Type
as mkopriva pointed. I end up with
package main
import (
"fmt"
"go/types"
)
type NewType int
func (v NewType) String() string {
return string(v)
}
func (v NewType) Underlying() types.Type {
return types.Type(v)
}
func main() {
var a *types.Array
a = types.NewArray(NewType(0), 2)
fmt.Println(a)
}
There is used new type with underlying int
. I guess I don't understand something yet in golang since for using such simple thing I had to write such useless methods as String
and Underlying
, they are useless because of implementation, I don't see the reason to be forced write such code. I appriciate if golang experts explain this stuff!