duanpanzhu2910 2018-10-28 16:29
浏览 87
已采纳

在Golang中为类型定义字符串输出

I'm wondering if there's a way through fmt to specify the way a string would get outputted for specific types. For example, I have a token struct that contains a bunch of information on the token, like token type (which is an int, but for clarity reasons, it would make more sense if I could output the name of the token type as a string).

So when I print a specific type of variable, is there a straightforward way to specify/implement the string output of such a type?

If that doesn't really make sense, Rust has an excellent form of doing so (from their doc)

use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

let origin = Point { x: 0, y: 0 };

println!("The origin is: {}", origin); // prints "The origin is: (0, 0)"
  • 写回答

1条回答 默认 最新

  • doupeng8494 2018-10-28 16:45
    关注

    You need to implement the interface Stringer, like this:

    import "fmt"
    
    type Point struct {
        x int
        y int
    }
    
    func (p Point) String() string {
        return fmt.Sprintf("(%d, %d)", p.x, p.y)
    }
    
    func main() {
        fmt.Println(Point{1, 2})
    }
    

    (Go Playground)

    In Go you don't specify which interfaces a type implements, you just implements the required methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作