dpxw7293
dpxw7293
2015-10-20 17:17
浏览 101
已采纳

在golang中,&和*有什么区别?

Can someone explain the difference between & and * in GO lang .. and provide examples of when & and * would be used to illustrate the difference? From what I have read, they both relate to accessing a variables memory location however i'm not sure when to use & or *.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • duanping6698
    duanping6698 2015-10-21 02:18
    已采纳

    Here is a very simple example, that illustrates how & and * are used. Note that * can be used for two different things 1) to declare a variable to be a pointer 2) to dereference a pointer.

    package main
    
    import "fmt"
    
    func main() {
        b := 6 
    
        var b_ptr *int // *int is used delcare variable
                       // b_ptr to be a pointer to an int
    
        b_ptr = &b     // b_ptr is assigned value that is the address
                           // of where variable b is stored
    
        // Shorhand for the above two lines is:
        // b_ptr := &b
    
        fmt.Printf("address of b_ptr: %p
    ", b_ptr)
    
        // We can use *b_ptr get the value that is stored
        // at address b_ptr, or dereference the pointer 
        fmt.Printf("value stored at b_ptr: %d
    ", *b_ptr)
    
    }
    

    Result:

    address of b_ptr: 0xc82007c1f0
    value stored at b_ptr: 6
    
    点赞 评论
  • doushan7077
    doushan7077 2015-10-20 17:23

    They are the opposite. As explained in the "Address operators" section of the spec:

    For an operand x of type T, the address operation &x generates a pointer of type *T to x. […]

    For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x. If x is nil, an attempt to evaluate *x will cause a run-time panic.

    In other words: & takes a variable (or other addressable entity) and returns a pointer that points to it, whereas * takes a pointer and returns the thing that it points to (unless it's nil, meaning it doesn't point to anything).

    点赞 评论
  • duanraotun1674
    duanraotun1674 2015-10-20 17:27

    & is the address of operator. * represent a pointer in some cases, in others it is used as the 'dereference operator'.

    So basically, if you do p := &SometType{} the address of operator is used to return the address of the object created with the composite literal statement SomeType{} if I were to remove it, I would no longer have a reference and instead be assigning the value directly to p. In this case p will be a *SomeType because that is the types who's address I took. If I declare a type with * in front of it, I'm designating it as a pointer to that type.

    Now the last remaining use is as a the deference operator, you don't use this much in Go in my experience but it was super common in C and C++. This is used to return the actual value rather, it's most often leverage for assignment. Because like if I have p and it is a *SomeType and locally I want to assign to an instance of SomeType then I'll need the following statement someType := *p so that the value is assigned to my value type.

    Hope that explanation helps. It's not the most technical one, rather my goal is to provide understanding of the common uses.

    点赞 评论
  • dongqiang2358
    dongqiang2358 2015-10-21 06:19

    & and * is used mainly in functions:

    package main
    
    import (
        "fmt"
    )
    
    type Person struct {
        name     string
        ageYears int
        areDays  int
    }
    
    func main() {
        john := Person{name: "John", ageYears: 46}
        toDays(&john)
        fmt.Println(john) //{John 46 16790}
        toDays2(john)
        fmt.Println(john) //{John 46 16790}
    }
    
    func toDays(p *Person) {
        p.areDays = p.ageYears * 365
    }
    
    func toDays2(p Person) {
        p.areDays = -1
    }
    
    点赞 评论
  • dtml3340
    dtml3340 2015-10-22 12:55

    & makes a pointer from a variable.

    * "fetches" the value stored where a pointer points to.

    For types, var *type means "*var is of the type type" (and without a variable, it simply means "a pointer to something of type".

    点赞 评论
  • duanpenpan5796
    duanpenpan5796 2018-05-22 13:28

    This helped me understand better, you can run the code in playground and play with it a bit to see how it behaves link here: https://play.golang.org/p/c7jxLJkdRDd (if link is deactivet in the future just copy paste code below)

    package main
    
    import (
        "fmt"
    )
    
    func main() {
    
        var a = 5
        var p = &a // copy by reference
        var x = a  // copy by value
    
        fmt.Println("a = ", a)   // a =  5
        fmt.Println("p = ", p)   // p =  0x10414020
        fmt.Println("*p = ", *p) // *p =  5
        fmt.Println("&p = ", &p) // &p =  0x1040c128
        fmt.Println("x = ", x)   // x =  5
    
        fmt.Println("
     Change *p = 3")
        *p = 3
        fmt.Println("a = ", a)   // a =  3
        fmt.Println("p = ", p)   // p =  0x10414020
        fmt.Println("*p = ", *p) // *p =  3
        fmt.Println("&p = ", &p) // &p =  0x1040c128
        fmt.Println("x = ", x)   // x =  5
    
        fmt.Println("
     Change a = 888")
        a = 888
        fmt.Println("a = ", a)   // a =  888
        fmt.Println("p = ", p)   // p =  0x10414020
        fmt.Println("*p = ", *p) // *p =  888
        fmt.Println("&p = ", &p) // &p =  0x1040c128
        fmt.Println("x = ", x)   // x =  5
    
        fmt.Println("
     Change x = 1")
        x = 1
        fmt.Println("a = ", a)   // a =  888
        fmt.Println("p = ", p)   // p =  0x10414020
        fmt.Println("*p = ", *p) // *p =  888
        fmt.Println("&p = ", &p) // &p =  0x1040c128
        fmt.Println("x = ", x)   // x =  1
    
        &p = 3 // error: Cannot assign to &p because this is the address of variable a
    }
    
    点赞 评论

相关推荐