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

问题描述 投票:0回答:1

我想知道是否有办法通过fmt来指定字符串输出特定类型的方式。例如,我有一个token结构,其中包含有关令牌的大量信息,如令牌类型(这是一个int,但为了清楚起见,如果我可以将令牌类型的名称输出为字符串,那将更有意义)。

因此,当我打印特定类型的变量时,是否有一种直接的方式来指定/实现这种类型的字符串输出?

如果这不是真的有意义,Rust有一个很好的形式(从他们的文档)

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)"
go gofmt
1个回答
2
投票

你需要实现接口Stringer,如下所示:

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})
}

(Qazxswpoi)

在Go中,您没有指定类型实现的接口,您只需实现所需的方法。

© www.soinside.com 2019 - 2024. All rights reserved.