Golang在结构之间切换

时间:2015-06-16 01:59:52

标签: struct go interface switch-statement

我是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”。

1 个答案:

答案 0 :(得分:4)

在您的示例中,您尝试将结构本身传递给函数而不是结构的实例。当我运行你的代码时,它不会编译。我同意上面的评论,但通过确保每个结构满足fmt.Stringer接口,可以更好地处理。

fmt.Stringer interface

代码的固定版本:

package main

import "fmt"

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"
}

func main() {
    l := Location{
        Street: "122 Broadway",
        City: "New York",
        State: "NY",
        Zip: "1000",
    }
    fmt.Println(Merge(l))
}

使用fmt.String的版本:

package main

import "fmt"

type Name struct {
    Title string
    First string
    Last  string
}

func (n *Name) String() string {
    return fmt.Sprintf("%s. %s %s", n.Title, n.First, n.Last)
}

type Location struct {
    Street string
    City   string
    State  string
    Zip    string
}

func (l *Location) String() string {
    return fmt.Sprintf("%s \n %s, %s %s", l.Street, l.City, l.State, l.Zip)
}

func main() {
    l := &Location{
        Street: "120 Broadway",
        City:   "New York",
        State:  "NY",
        Zip:    "1000",
    }
    fmt.Println(l)

    n := &Name{
        Title: "Mr",
        First: "Billy",
        Last:  "Bob",
    }
    fmt.Println(n)
}