3

For code append(slice1, 1), Go compile will give error "append(...) evaluated but not used". And we have to use like slice1 = append(slice1,1) because append doesn't modify slice1 and it will return a new slice.

I think it is a good hint since this will prevent lots of bug since we often didn't know function like append will change original array or not. In JavaScript array1.push('item') will change array1 in place and return new length of the array.

I want to utilize this kind of code checking:

func appendStr(str string, tail string) string {
    b := str + tail
    return b
}
a := "a"
appendStr(a, "b")

But Go compiler didn't give error. So compiler do some special checking on append method? Since Go pass parameter by value, Compiler should know appendStr has no change to modify pass-in parameter.

fkpwolf
  • 373
  • 4
  • 13

2 Answers2

5

append() is special because it's a built-in function, and the compiler does extra check on it. It is very rarely useful to not use the return value of append(), so the Go authors decided to make it a compile-time error if it is not used.

On the other hand, calling "ordinary" functions which have return values often have "side effects", and it's common to just call a function for its "side effects" and not use its return values. A very common example is fmt.Println(): you often print something to the console, and you rarely (if ever) check if that succeeds or how many bytes were actually written.

The language spec allows you to not use the return values of functions, so it's valid to do so and you can't force the compiler to make an error or warning out of it, you can't make the compiler to "mark" valid code with error.

See related question: Return map like 'ok' in Golang on normal functions

icza
  • 389,944
  • 63
  • 907
  • 827
2

The way this is typically done in Go is by using an extra tool, a linter if you will. go vet is commonly used to point out things in the code that "don't look right" and which are probably bugs. It seems that you cannot make it check your own functions out-of-the-box, only things like fmt.Sprintf will be checked.

Another tool is errcheck which reports ignored errors.

You could fork one of these tools and insert your own function(s) there, then make everyone check their code before committing it to source control or check it automatically.

gonutz
  • 5,087
  • 3
  • 22
  • 40
  • And of course there's the mother-of-all-linters, https://github.com/alecthomas/gometalinter – Adrian Aug 02 '18 at 12:04