2016-10-17 46 views
1

假設我有兩個文件。如何在兩種自定義類型之間進行投射

hello.go

package main 


type StringA string 


func main() { 

    var s StringA 
    s = "hello" 
    s0 := s.(StringB) <---- somehow cast my StringA to StringB. After all, they are both strings 
    s0.Greetings() 

} 

bye.go

package main 

import "fmt" 

type StringB string 



func (s StringB) Greetings(){ 

    fmt.Println(s) 

} 

和編譯該是這樣的:

go build hello.go bye.go 

如何投StringA的類型StringB

感謝

回答

1

可以使用的方式s0 := StringB(s)在其他語言的構造函數,但這裏只是其他的方法來創建兼容的類型,如[]byte("abc")

你的代碼可能看起來像:

type StringA string 

type StringB string 

func (s StringB) Greetings(){ 
    fmt.Println(s) 

} 

func main() { 
    var s StringA 
    s = "hello" 
    s0 := StringB(s) 
    s0.Greetings() 
} 

完整示例:https://play.golang.org/p/rMzW5FfjSE

相關問題