How can I pass dictionary as list of arguments for function like in Python 3 in Go?
Python 3:
def bar(a,b,c):
print(a,b,c)
args={c: 1, b: 2, a: 3}
bar(**args)
Go blank:
func bar( a, b, c int) {
fmt.Printf("%d, %d, %d", a, b, c)
}
func main(){
args := make(map[string]int)
args["a"] = 3
args["b"] = 2
args["c"] = 1
// what next ?
}
A named argument consists of an argument name followed by a colon and an equal sign (:=), followed by the argument value. Named arguments are especially useful when you are calling a procedure that has optional arguments.
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter names. A keyword argument is preceded by a parameter and the assignment operator, = . Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
With named arguments, the call site would rather look like that: displayCoolName(firstName = "James", lastName = "Bond"); It has the advantage of being more explicit so that you don't mix up the order of the parameters.
Golang supports two different ways to pass arguments to the function i.e. Pass by Value or Call by Value and Pass By Reference or Call By Reference. By default, Golang uses the call by value way to pass the arguments to the function.
I don't believe this is possible. You'd need to use a struct to do anything even remotely close to this (and it is a remote likeness)
type Args struct {
A, B, C int
}
func bar(args *Args) {
fmt.Printf("%d, %d, %d", args.A, args.B, args.C)
}
func main() {
args := new(Args)
args.A = 3
args.B = 2
args.C = 1
bar(args)
}
In addition to the other answers, which I see no need to repeat, be aware that Go will auto-unpack function calls with multiple return arguments provided:
(That is, the types of the function's argument list is identical to the other function's return list).
func Args() (a int, b int, c int) {
return 1,2,3
}
func Bar(a,b,c int) {
fmt.Println(a,b,c)
}
func main() {
Bar(Args())
}
Will print 1,2,3
. Obviously this example is a tad silly, but I find this covers most cases of tuple and dict unpacking as arguments in Python, which tend to be a quick and dirty way of passing one function's return values as another function's arguments.
For completeness sake you can either use what dskinner said, or if you want a "dictionary" (called map in Go) you could use one easily, for example
:
package main
import "log"
type ArgsMap map[string]interface{}
func bar(am ArgsMap) {
if v, ok := am["foo"].(string); ok {
log.Println("bar", v)
} else {
log.Println("bar no foo")
}
}
// Or
type Args struct {
foo string
boo int
a, b, c float32
}
func bar2(a Args) {
if a.foo != "" {
log.Println("bar2", a.foo)
} else {
log.Println("bar2 no foo")
}
}
func main() {
bar(ArgsMap{"foo": "map", "blah": 10})
bar(ArgsMap{})
bar2(Args{foo: "struct"})
bar2(Args{})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With