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.

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

报告相同问题?

悬赏问题

  • ¥15 vhdl+MODELSIM
  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题