如何在Go中定义自己的类型转换器?

时间:2012-06-22 13:12:52

标签: go

我正在定义一种类型。我注意到Go有一个名为uint8的类型和一个名为uint8的函数,它创建了一个uint8值。

但是当我尝试为自己做这件事时:

12:    type myType uint32

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

我收到错误

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

如果我将其更改为有效的func newMyType,但感觉我是二等公民。我可以使用与类型类型相同的标识编写类型构造函数吗?

1 个答案:

答案 0 :(得分:5)

uint8()不是函数也不是构造函数,而是type conversion

对于原始类型(或其他明显的转换,但我不知道确切的定律),您不需要创建构造函数。

你可以这样做:

type myType uint32
v := myType(33)

如果您在创建值时要执行操作,则应使用“make”功能:

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))
}

只有在返回指针时才能使用函数newMyType