Logo

Programming-Idioms

History of Idiom 20 > diff from v34 to v35

Edit summary for version 35 by :
[Go] "for i" more idiomatic than "for i, _"

Version 34

2016-02-20, 18:48:10

Version 35

2016-02-20, 23:33:38

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Code
func search(m [][]int, x int) (bool, int, int) {
	for i, _ := range m {
		for j, v := range m[i] {
			if v == x {
				return true, i, j
			}
		}
	}
	return false, 0, 0
}
Code
func search(m [][]int, x int) (bool, int, int) {
	for i := range m {
		for j, v := range m[i] {
			if v == x {
				return true, i, j
			}
		}
	}
	return false, 0, 0
}
Comments bubble
Go functions may return multiple values.
This function returns 3 values : one to indicate if x was found or not, and two for the coordinates.
Comments bubble
Go functions may return multiple values.
This function returns 3 values : one to indicate if x was found or not, and two for the coordinates.
Demo URL
http://play.golang.org/p/JNCbBqWM16
Demo URL
http://play.golang.org/p/wFqwygbLje