Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Computer Science Introduction to Algorithms Algorithms in Code Linear Search Implementations

Golang code example is not valid

func linearsearch(data []int, key int) bool {
    for idx, item := range data {
        if item == key {
            return idx
        }
    }
    return nil
}

This code would not be able to compile as the return value expected is a bool, but the function returns either an int or nil. The following would be valid:

func linearsearch(data []int, key int) bool {
    for _, item := range data {
        if item == key {
            return true
        }
    }
    return false
}

You may want to update the example for anyone else looking to write in Go!

1 Answer

Steven Parker
Steven Parker
211,076 Points

You're right about the errors, and your suggested code would run just fine. But the purpose of the function is to return the index of the found item and a bool does not handle this.

So I would suggest having the function return an "int" value and using -1 to indicate "not found" as is done for some of the other language versions:

func linearsearch(data []int, key int) int {
    for idx, item := range data {
        if item == key {
            return idx
        }
    }
    return -1
}

I'm also passing this along to the staff in a bug report, hopefully it will be fixed soon.

Steven Parker
Steven Parker
211,076 Points

Pasan Premaratne — I'm also tagging you in case you'd like to look into this yourself.

Pasan Premaratne
Pasan Premaratne
Treehouse Teacher

Thanks folks! Go is not my area of expertise so I'll poke over this and update the docs as needed :)