The spec does not allow you to specify parameter names when calling a function. You can only list the values you wish to pass as arguments. You have to specify values for all parameters (except for the variadic parameter), and you have to list them in the expected order.
The closest you can get to what you want is passing a struct. Create a struct type that wraps your current parameters, and change your function to accept a value of that struct (or a pointer to it):
type Params struct {
name, address, nick string
age, value int
}
func MyFunction(p Params) {
// perform some operations
}
func main() {
MyFunction(Params{
name: "Bob",
address: "New York",
nick: "Builder",
age: 30,
value: 1000,
})
}
Then of course you have to refer to these fields using a selector on the p
parameter, e.g.:
func MyFunction(p Params) {
// perform some operations
fmt.Printf("%s lives in %s.\n", p.name, p.address)
}
Also note that as an extra "gain" (or burden), the "parameters" (which are the fields of the struct parameter) become optional and unordered: you are not forced to specify a value to all the fields, and you can list the fields in any order you like.
You can also call it like this:
MyFunction(Params{
name: "Alice",
address: "Washington",
})
Output of the above calls (try it on the Go Playground):
Bob lives in New York.
Alice lives in Washington.
If you don't want to (or can't) change the function to accept a struct parameter, then you may leave it as-is, and create a new, helper function which will have this struct parameter, and all it would do is call the original function, passing the appropriate fields as arguments:
func MyFunction(name, address, nick string, age, value int) {
// perform some operations
}
func MyFunction2(p Params) {
MyFunction(p.name, p.address, p.nick, p.age, p.value)
}
And then you can call MyFunction()
indirectly like this:
MyFunction2(Params{
name: "Bob",
address: "New York",
nick: "Builder",
age: 30,
value: 1000,
})
See this related question: Getting method parameter names in Golang