Joe
Joe

Reputation: 47729

How do I define my own type converters in Go?

I'm defining a type. I notice that Go has a type called uint8 and a function called uint8 which 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 the error

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

If I change it to func newMyType that works but it feels like I'm a second class citizen. Can I write type constructor functions with the same ident as type type?

Upvotes: 4

Views: 185

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382434

uint8() isn't a function nor a constructor, but a type conversion.

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

You can simply do this :

type myType uint32
v := myType(33)

If you have operations to do when creating your value, you should use a "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))
}

Naming a function newMyType should only be used when returning a pointer.

Upvotes: 5

Related Questions