Named parameters: Difference between revisions

Added Go
(Removed {{omit from|Go}} template as named parameters can in fact be simulated in the language.)
(Added Go)
Line 495:
call b_sub(1, 2) ! ok: arg1 is 1, arg2 is 2
call b_sub(arg2=2, arg1=1) ! the same as the previous line</lang>
 
=={{header|Go}}==
Although Go doesn't support named parameters as such, they can be simulated using a struct with fields corresponding in name and type to the desired parameters.
 
A struct literal can then be passed to the function labelling the individual fields with their names. The fields need not appear in the same order as they are declared and, if one or more are omitted, they are given their 'zero' values.
 
Here's a simple example.
<lang go>package main
 
import (
"fmt"
)
 
type params struct {x, y, z int}
 
func myFunc(p params) int {
return p.x + p.y + p.z
}
 
func main() {
r := myFunc(params{x: 1, y: 2, z: 3}) // all fields, same order
fmt.Println("r =", r)
s := myFunc(params{z: 3, y: 2, x: 1}) // all fields, different order
fmt.Println("s =", s)
t := myFunc(params{y: 2}) // only one field, others set to zero
fmt.Println("t =", t)
}</lang>
 
{{out}}
<pre>
r = 6
s = 6
t = 2
</pre>
 
=={{header|Haskell}}==
9,476

edits