2016-10-17 39 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

相关问题