duanqu9279 2012-06-22 13:12
浏览 18
已采纳

如何在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?

  • 写回答

1条回答 默认 最新

  • dongzaotiao2863 2012-06-22 13:20
    关注

    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
    ", b)
        fmt.Println("type of b :", reflect.TypeOf(b))
        fmt.Printf("%+v
    ", c)
        fmt.Println("type of c :", reflect.TypeOf(c))
    }
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法