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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵