How to dereference fields when printing?

后端 未结 3 592
余生分开走
余生分开走 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: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).

提交回复
热议问题