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 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试