I've been reading the [golang-book]: http://www.golang-book.com and completing the excercises as I go along. In Chapter 6, there is an exercise that must find the smallest element in an unsorted list[x].
I have the following code but somehow I don't know why the method length (len) gives me an error on line 14: x.len undefined (type []int has no field or method len)
package main
import "fmt"
func main() {
x := []int{
48, 96, 86, 68,
57, 82, 63, 70,
37, 34, 83, 27,
19, 97, 9, 17,
}
small := x[0]
for i := 1; i < x.len(); i++ {
if x[i] < small {
fmt.Println(x[i])
}
}
}
The logic I used was Googled so perhaps there is no len method on arrays? Any help is greatly appreciated.
Arrays and slices do not have a len() method. The len() function is a language built-in.
So your code
for i := 1; i < x.len(); i++ {
Should be
for i := 1; i < len(x); i++ {
Here is a working version in the playground.
package main
import "fmt"
func main(){
x := []int{
48,96,86,68,
57,82,63,70,
37,34,83,27,
19,97, 9,17,
}
small := x[0]
for i := 1; i < len(x); i++ {
if x[i] < small {
fmt.Println(x[i]);
}
}
}
len()
isn't a method of a slice. It's a global function. You want to say len(x)
.
package main
import "fmt"
func main() {
x := []int{
48, 96, 86, 68,
57, 82, 63, 70,
37, 34, 83, 27,
19, 97, 9, 17,
}
small := x[0]
for i := 1; i < len(x); i++ {
if x[i] < small {
fmt.Println(x[i])
}
}
}
In fact, array- and slice-types can have a len()
method, like this:
http://play.golang.org/p/CkU4LJZgUb
package main
import "fmt"
type SliceType []int
func (s SliceType) len() int {
return len(s)
}
func main() {
s := SliceType{1, 2, 3, 4, 5, 6, 7, 8, 9}
for i := 0; i < s.len(); i++ {
fmt.Println(s[i])
}
}
The code you found is probably an implementation of container/list
or container/ring
, both of which specify a Len()
method.
Primitive slices and arrays, though, don't have any methods attached to them and you must use the built-in function len()
.