How can I get the string representation of a struct?

前端 未结 5 814
闹比i
闹比i 2021-01-30 16:04

For my application, it does not matter if the string is human readable or not.

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 16:16

    Attaching a String() function to a named struct allows us to convert a struct to a string.

    package main
    
    import "fmt"
    
    type foo struct {
        bar string
    }
    
    func (f foo) String() string {
        return fmt.Sprintf("Foo Says: %s", f.bar)
    }
    
    func main() {
        fmt.Println(foo{"Hello World!"})
    }
    
    output:
    Foo Says: Hello World!
    

提交回复
热议问题