top | item 14668580

(no title)

alexhornbake | 8 years ago

Naming the return value in the function signature will both allocate the named variable, as well as make it the default variable to return.

Returning a new unnamed variable for every return will cause all of the unnamed variables to be allocated.

It's interesting, I don't use this feature of the language... my default way to write this would have been:

  func NoNamedReturnParams(i int) (*objectInfo) {
        obj := &objectInfo{}
	if i == 1 {
		// Do one thing
		return obj
	}

	if i == 2 {
		// Do another thing
		return obj
	}

	if i == 3 {
		// Do one more thing still
		return obj
	}

	// Normal return
	return obj
  }

discuss

order

19eightyfour|8 years ago

I had a bit of a play around with it. It's pretty powerful being able to see <func name> <params type> <return type> in one line ( or possibly multi line )

It really hammers home the concept that a function is a transformation, and of what into what. And I think this syntax would probably encourage pure functions. And it's so useful to allocate the return in the top line. I really like go.

cyphar|8 years ago

I'm fairly sure that almost every statically typed language has function definitions like that. C, C++, Java, Go, Rust and so on all have that style of function declaration.

Named returns are a Go thing mainly because of defer.

ryeguy|8 years ago

What language that has static types doesn't have the func, params, and return type in one line?