简体   繁体   中英

how to cast between two custom types

Suppose I have two files.

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)

}

And compile this like this:

go build hello.go bye.go

How do I cast StringA to the type StringB ?

Thanks

You can use the way s0 := StringB(s) in other languages is a constructor but here is just other way to create compatible types, like []byte("abc")

Your code may looks like:

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

full example: https://play.golang.org/p/rMzW5FfjSE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM