Golang 在结构之间切换

我是 golang 的新手,我正在尝试创建一个函数,该函数基于它所使用的结构,将使用 Sprintf 返回一个格式化的字符串


type Name struct {

    Title string

    First string

    Last  string

}


type Location struct {

    Street string

    City   string

    State  string

    Zip    string

}


func Merge(m interface{}) string {

    switch m.(type) {

    case *Location:

        return fmt.Sprintf("%s \n %s, %s %s", m.(*Location).Street, m.(*Location).City, m.(*Location).State, m.(*Location).Zip)

    case *Name:

        return fmt.Sprintf("%s. %s %s", m.(*Name).Title, m.(*Name).First, m.(*Name).Last)

    }

    return "Not Applicable"

}


fmt.Println(Merge(Location))

我Not Applicable从我的PrintLn. 在代码的一个版本中,我相信消息是“ out of index”。


泛舟湖上清波郎朗
浏览 133回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go