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

huangapple go评论68阅读模式
英文:

How do I define my own type converters in Go?

问题

我正在定义一个类型。我注意到Go语言有一个叫做uint8的类型和一个叫做uint8的函数,用于创建一个uint8的值。

但是当我尝试自己这样做时:

12:    type myType uint32

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

我得到了错误信息:

./thing.go:14: myType在此块中重新声明
	之前的声明在./thing.go:12中

如果我将其改为func newMyType,那样可以工作,但感觉自己像是一个二等公民。我能否使用与类型相同的标识符编写类型构造函数?

英文:

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?

答案1

得分: 5

uint8()不是一个函数也不是一个构造函数,而是一种类型转换

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

您可以简单地这样做:

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("b的类型:", reflect.TypeOf(b))
    fmt.Printf("%+v\n", c)
    fmt.Println("c的类型:", reflect.TypeOf(c))
}

只有在返回指针时才应该将函数命名为newMyType

英文:

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.

huangapple
  • 本文由 发表于 2012年6月22日 21:12:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/11156885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定