Skip to content

cannot assign to an element of an array which is returned from a function #12650

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bigwhite opened this issue Sep 17, 2015 · 2 comments
Closed

Comments

@bigwhite
Copy link

I' m doubting about the code below:

package main

func getSlice() []int {
    var a [5]int
    return a[:]
}

func getArray() [5]int {
    var a [5]int
    return a
}

func getPointerToArray() *[5]int {
    var a [5]int
    return &a
}

func main() {
    getSlice()[0] = 1
    getArray()[0] = 1
    getPointerToArray()[0] = 1
}

both "getSlice()[0] = 1" and "getPointerToArray()[0] = 1" are ok for compiler.
but getArray()[0] can not go through.

The go 1.5 compiler give error:
"cannot assign to getArray()[0]"

Is this a problem?if not, Who could tell me why we can't not use the form like above! 3ks!

@mdempsky
Copy link
Contributor

Questions like this are better addressed by the golang-nuts mailing list, but the short summary is the Go programming language specification says the assignment getArray()[0] = 1 is not allowed.

Assignments: "Each left-hand side operand must be addressable, a map index expression, or (for = assignments only) the blank identifier."

Address operators: "The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array."

getSlice()[0] is a slice indexing operation, so it's addressable, so the assignment is valid.

getPointerToArray()[0] is short-hand for (*getPointerToArray())[0], and pointer indirections are addressable, so this is an array indexing of an addressable array.

getArray()[0], however, is an array indexing of a non-addressable array, so the Go compiler is rightfully rejecting the statement as invalid.

@bradfitz
Copy link
Contributor

See the language spec's part about addressability.

We can move this discussion to the golang-nuts mailing list.

@golang golang locked and limited conversation to collaborators Sep 22, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants