Dijkstra
Dijkstra

Reputation: 2530

Dereferencing pointers in Go

I'm confused as to why line 15 is not valid. Why can't a pointer to a big.Int be dereferenced, whilst a pointer to an int can?

package main

import (
    "fmt"
    "big"
)

func main() {
    var c *int = getPtr()
    fmt.Println(c)
    fmt.Println(*c)

    var d *big.Int = big.NewInt(int64(0))
    fmt.Println(d)

    // does not compile - implicit assignment of big.Int
    // field 'neg' in function argument
    //fmt.Println(*d)
}

func getPtr() *int {
    var a int = 0
    var b *int = &a
    return b
}

Upvotes: 4

Views: 3091

Answers (1)

Evan Shaw
Evan Shaw

Reputation: 24547

It's because Int is a struct with unexported fields. When you pass a struct by value to a function, you're making a copy of it. The Go spec states that for this to be legal

...either all fields of T must be exported, or the assignment must be in the same package in which T is declared. In other words, a struct value can be assigned to a struct variable only if every field of the struct may be legally assigned individually by the program.

Upvotes: 5

Related Questions