2016-10-17 2 views
1

Angenommen, ich habe zwei Dateien.wie zwischen zwei benutzerdefinierten Typen zu konvertieren

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) 

} 

Und kompilieren dies dies wie:

go build hello.go bye.go 

Wie ich StringAStringB auf die Art werfen Sie?

Dank

Antwort

1

Sie die Art und Weise s0 := StringB(s) in anderen Sprachen hier ein Konstruktor verwenden kann, aber nur auf andere Weise kompatible Typen zu erstellen, wie []byte("abc")

kann Ihr Code sieht aus wie:

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() 
} 

vollständiges Beispiel: https://play.golang.org/p/rMzW5FfjSE

Verwandte Themen