在Go中将自定义类型转换为字符串 [英] Converting a custom type to string in Go

查看:443
本文介绍了在Go中将自定义类型转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个奇怪的示例中,有人创建了一个实际上只是字符串的新类型:

In this bizarre example, someone has created a new type which is really just a string:

type CustomType string

const (
        Foobar CustomType = "somestring"
)

func SomeFunction() string {
        return Foobar
}

但是,此代码无法编译:

However, this code fails to compile:

不能在返回参数中使用Foobar(CustomType类型)作为类型字符串

cannot use Foobar (type CustomType) as type string in return argument

如何修复SomeFunction,使其能够返回Foobar的字符串值("somestring")?

How would you fix SomeFunction so that it is able to return the string value of Foobar ("somestring") ?

推荐答案

值转换为字符串:

func SomeFunction() string {
        return string(Foobar)
}

这篇关于在Go中将自定义类型转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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