2015-08-29 05:10
浏览 21


I'm using a package and instead of returning a string, it returns a economy.ClassId You can see here

I want to pass the economy.ClassId which is just a string of numbers like "531569319" to a function that takes a string not a economy.ClassId so is there a way to convert this type to a string or no. Thanks.

I know you could like strconv.FormatUint() but what would I use for a custom type.

图片转代码服务由CSDN问答提供 功能建议

我使用的是包,而不是返回 string ,它返回的是< code> economy.ClassId 您可以在此处

我想将只是一个数字字符串的 economy.ClassId 传递给采用字符串而不是 economy.ClassId的函数,例如“ 531569319” 因此有一种方法可以将这种类型转换为字符串或否。 谢谢。

我知道您可能会喜欢 strconv.FormatUint(),但是自定义类型将使用什么。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongmu3457 2015-08-29 05:21

    ClassId is declared as type ClassId uint64, so although a ClassId isn't exactly the same as a uint64, they have the same underlying type, and you can therefore convert from one to the other. To convert a value x to type T (when permitted), you write T(x). So, in your case:

     funcThatTakesAString(strconv.FormatUint(uint64(classId), 10))
    打赏 评论
  • doutang1873 2015-08-29 06:40

    Another approach that is perhaps more idiomatic is to use fmt.Sprintf using Go's format string specification.

    Two examples...

    The following converts the classId into a string base 10 number:

    classIDStr := fmt.Sprintf("%d", classId)

    The following converts it into a string hexadecimal number, with a-f digits in lower case:

    classIDHex := fmt.Sprintf("%x", classId)

    打赏 评论
  • doutidi5037 2015-08-29 07:37

    more generally you could implement the stringer interface on your type

    func (c ClassId) String() string {
        return strconv.FormatUint(uint64(c),10)

    and use that otherFunc(classId.String())

    PS: also acronymes (ID) should be all capitals

    打赏 评论

相关推荐 更多相似问题