Go中的ToString()函数 [英] ToString() function in Go

查看:539
本文介绍了Go中的ToString()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

strings.Join 函数仅包含字符串切片:

  s:= [] string {foo,bar,baz} 
fmt.Println(strings.Join(s,,))

但能够传递实现 ToString()函数的任意对象。

 类型ToStringConverter接口{
ToString()字符串
}

在Go中是否有这样的内容,或者是否必须修饰现有类型,如 int 使用ToString方法,并在 strings.Join

前面写一个包装器。 func Join(a [] ToStringConverter,sep string)字符串


解决方案

String()字符串方法附加到任何指定类型,并享受任何自定义的ToString功能:

  package main 

importfmt

类型bin int

func(b bin)String()s tring {
return fmt.Sprintf(%b,b)
}

func main(){
fmt.Println(bin(42))
}

游乐场: http://play.golang.org/p/Azql7_pDAA






输出

  101010 


The strings.Join function takes slices of strings only:

s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))

But it would be nice to be able to pass arbitrary objects which implement a ToString() function.

type ToStringConverter interface {
    ToString() string
}

Is there something like this in Go or do I have to decorate existing types like int with ToString methods and write a wrapper around strings.Join?

func Join(a []ToStringConverter, sep string) string

解决方案

Attach a String() string method to any named type and enjoy any custom "ToString" functionality:

package main

import "fmt"

type bin int

func (b bin) String() string {
        return fmt.Sprintf("%b", b)
}

func main() {
        fmt.Println(bin(42))
}

Playground: http://play.golang.org/p/Azql7_pDAA


Output

101010

这篇关于Go中的ToString()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆