dsjgk330337 2017-09-07 23:14
浏览 192
已采纳

Golang:将结构作为函数的参数传递

Trying to teach myself some Go by following an online course. And I'm trying to go a bit off course to expand on my learning a bit.

The course had us writing a simple function using a couple variables and the function would take the two variables and print out a line. So I had:

    func main() {

        var greeting := "hello"
        var name := "cleveland"

        message := printMessage(greeting,name)
        fmt.Println(message)

    }

    func printMessage(greeting string, name string) (message string) {

        return greeting + " " + name + "!"

    }

Later the course introduced a way to create an pseudo-array of strings using the using the

    func sayHello (cities ...string) (message string) {
        for _, city := range cities {
            message := printMessage("hello", city)
            fmt.Println(message)
        }
    }

I would like to create a struct with different greetings and pass those into the sayHello function. So the struct and the variables would looks something like this:

    type cityInfo struct {
        greeting string
        name string
        wins float32
        gamesPlayed float32
    }

    city1 := cityInfo{"hello", "cleveland"}
    city2 := cityInfo{"good morning", "atlanta"}
    ...and so on

How do I format the function to pass those structs into the function so that I can iterate on the number of structs and get the greetings and names using city.greeting and city.name? Does this question make sense?

  • 写回答

2条回答 默认 最新

  • doushi7819 2017-09-08 00:00
    关注

    Function argument type can be any valid type:

    func sayHello (cities ...cityInfo) {
        for _, city := range cities {
            message := printMessage(city.greeting, city.name)
            fmt.Println(message)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看