mwdowns
mwdowns

Reputation: 85

Golang: Passing structs as parameters of a function

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?

Upvotes: 2

Views: 9057

Answers (2)

Cat J.
Cat J.

Reputation: 1

One solution would be to create an interface and a greeting method.

For example:

type Greetable interface {
    Greeting() string
    Name() string
}

You would then implement the Greeting and Name methods in your struct (this would immediately implement the Greetable interface, due to the way that Go handles interfaces):

type cityInfo struct {
    name     string
    greeting string
}

func (city *cityInfo) Greeting() string {
    return city.greeting 
}

func (city *cityInfo) Name() string { 
    return city.name 
}

And then your function would just accept anything that implements Greetable:

func sayHello(greetables ...Greetable) (message string)

And use the Name() and Greeting() methods instead.

Upvotes: 0

marklap
marklap

Reputation: 481

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

Upvotes: 4

Related Questions