2012-06-22 45 views
4

我正在定義一個類型。我注意到Go有一個叫uint8的類型和一個叫uint8的函數,它創建一個uint8值。如何在Go中定義自己的類型轉換器?

但是,當我嘗試自己做這一點:

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的作品,但感覺就像我的第二類公民。我可以使用與type類型相同的ident來編寫類型構造函數嗎?

回答

5

uint8()不是功能也不是構造函數,而是type conversion

對於原始類型(或其他明顯的轉換,但我不知道確切的法則),您不需要創建構造函數。

您可以簡單地這樣做:

type myType uint32 
v := myType(33) 

如果您有業務創造你的價值的時候,你應該使用一個「做」的功能做到:

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只應在返回指針時使用。

+0

轉換需要一些位調,我想這是一個比C風格強大的構造函數。也許類型轉換不是我想要的。 – Joe

+0

順便說一句,我的例子確實說明它需要一個'[]字節'。 – Joe

+0

就像我擔心的一樣。留言Merci! – Joe

相關問題