How to define your own type converters in Go?

I determine the type. I noticed that Go has a type called uint8 and a function called uint8 that creates a uint8 value.

But when I try to do this for myself:

 12: type myType uint32 14: func myType(buffer []byte) (result myType) { ... } 

I get an error

 ./thing.go:14: myType redeclared in this block previous declaration at ./thing.go:12 

If I change it to func newMyType , which works, but it looks like I'm a second-class citizen. Can I write type constructor functions with the same type as the type of the type?

+4
source share
1 answer

uint8() not a function or constructor, but a type conversion .

For a primitive type (or other obvious transformations, but I don't know the exact law), you do not need to create a constructor.

You can simply do this:

 type myType uint32 v := myType(33) 

If you perform operations while creating your value, you should use the "make" function:

 package main import ( "fmt" "reflect" ) type myType uint32 func makeMyType(buffer []byte) (result myType) { result = myType(buffer[0]+buffer[1]) return } func main() { b := []byte{7, 8, 1} c := makeMyType(b) fmt.Printf("%+v\n", b) fmt.Println("type of b :", reflect.TypeOf(b)) fmt.Printf("%+v\n", c) fmt.Println("type of c :", reflect.TypeOf(c)) } 

The naming of the newMyType function should only be used when returning a pointer.

+5
source

All Articles