How to dereference fields when printing?

后端 未结 3 591
余生分开走
余生分开走 2021-01-04 02:14

http://play.golang.org/p/joEmjQdMaS

package main

import \"fmt\"

type SomeStruct struct {
    somePointer *somePointer
}
type somePointer struct {
    field         


        
相关标签:
3条回答
  • 2021-01-04 02:43

    You're attempting to print a struct that contains a pointer. When you print the struct, it's going to print the values of the types contained - in this case the pointer value of a string pointer.

    You can't dereference the string pointer within the struct because then it's no longer accurately described by the struct and you can't dereference the struct because it's not a pointer.

    What you can do is dereference the string pointer, but not from within the struct.

    func main() {
        pointer := SomeStruct{&somePointer{"I want to see what is in here"}}.somePointer
        fmt.Println(*pointer)
    }
    

    output: {I want to see what is in here}

    You can also just print the specific value from within the Println:

    func main() {
        fmt.Println(SomeStruct{&somePointer{"I want to see what is in here"}}.somePointer)
    }
    

    output: &{I want to see what is in here}

    Another thing to try is Printf:

    func main() {
        structInstance := SomeStruct{&somePointer{"I want to see what is in here"}}
        fmt.Printf("%s",structInstance)
    }
    

    output: {%!s(*main.somePointer=&{I want to see what is in here})}

    0 讨论(0)
  • 2021-01-04 02:48
    package main
    
    import (
        "fmt"
    )
    
    
    type SomeTest struct {
        someVal string
    }
    
    func (this *SomeTest) String() string {
        return this.someVal
    }
    
    func main() {
        fmt.Println(&SomeTest{"You can see this now"})
    }
    

    Anything that provides the Stringer interface will be printed with it's String() method. To implement stringer, you only need to implement String() string. To do what you want, you'd have to implement Stringer for SomeStruct (in your case, dereference somePointer and do something with that).

    0 讨论(0)
  • 2021-01-04 02:51

    There is a great package called go-spew. Does exactly what you want.

    package main
    
    import (
      "github.com/davecgh/go-spew/spew"
    )
    
    type (
      SomeStruct struct {
        Field1 string
        Field2 int
        Field3 *somePointer
      }
      somePointer struct {
        field string
      }
    )
    
    func main() {
      s := SomeStruct{
        Field1: "Yahoo",
        Field2: 500,
        Field3: &somePointer{"I want to see what is in here"},
      }
      spew.Dump(s)
    
    }
    

    Will give you this output:

    (main.SomeStruct) {
     Field1: (string) "Yahoo",
     Field2: (int) 500,
     Field3: (*main.somePointer)(0x2102a7230)({
      field: (string) "I want to see what is in here"
     })
    }
    
    0 讨论(0)
提交回复
热议问题