【问题标题】:Converting a custom type to string in Go在 Go 中将自定义类型转换为字符串
【发布时间】:2018-02-04 02:32:48
【问题描述】:

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

type CustomType string

const (
        Foobar CustomType = "somestring"
)

func SomeFunction() string {
        return Foobar
}

但是,这段代码编译失败:

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

您将如何修复 SomeFunction 以便它能够返回 Foobar ("somestring") 的字符串值?

【问题讨论】:

  • 创建一个只是字符串的类型并不是那么奇怪。例如,如果您知道某个字符串始终是国家/地区名称,您可以创建一个type Country string;这将使代码更易于阅读。
  • @Akavall 如何将Country 类型限制为已知的值列表?我们能做到吗?

标签: string go type-conversion


【解决方案1】:

Convert将值转为字符串:

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

【讨论】:

  • 如果无法控制字符串类型别名,则非常有用;在那些情况下添加String 方法是不可能的。
【解决方案2】:

最好为Customtype 定义一个String 函数 - 随着时间的推移,它可以让您的生活更轻松 - 随着结构的发展,您可以更好地控制事物。如果你真的需要SomeFunction,那就让它返回Foobar.String()

   package main

    import (
        "fmt"
    )

    type CustomType string

    const (
        Foobar CustomType = "somestring"
    )

    func main() {
        fmt.Println("Hello, playground", Foobar)
        fmt.Printf("%s", Foobar)
        fmt.Println("\n\n")
        fmt.Println(SomeFunction())
    }

    func (c CustomType) String() string {
        fmt.Println("Executing String() for CustomType!")
        return string(c)
    }

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

https://play.golang.org/p/jMKMcQjQj3

【讨论】:

    【解决方案3】:

    对于每一个类型T,都有一个对应的转换操作T(x) 将值 x 转换为类型 T。从一种类型转换为 如果两者具有相同的基础类型,或者如果两者都具有相同的基础类型,则允许另一个 是指向相同变量的未命名指针类型 基础类型;这些转换会改变类型,但不会改变 值的表示。如果 x 可分配给 T,则转换 是允许的,但通常是多余的。 - 取自The Go Programming Language - by Alan A. A. Donovan

    根据您的示例,这里有一些将返回值的不同示例。

    package main
    
    import "fmt"
    
    type CustomType string
    
    const (
        Foobar CustomType = "somestring"
    )
    
    func SomeFunction() CustomType {
        return Foobar
    }
    func SomeOtherFunction() string {
        return string(Foobar)
    }
    func SomeOtherFunction2() CustomType {
        return CustomType("somestring") // Here value is a static string.
    }
    func main() {
        fmt.Println(SomeFunction())
        fmt.Println(SomeOtherFunction())
        fmt.Println(SomeOtherFunction2())
    }
    

    它会输出:

    somestring
    somestring
    somestring
    

    The Go Playground link

    【讨论】:

      【解决方案4】:

      你可以这样转换:

      var i int = 42 var f float64 = float64(i)

      检查here

      你可以这样返回:

      return string(Foobar)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-27
        • 2011-05-15
        • 2019-11-22
        • 2017-06-22
        • 2020-03-17
        • 2011-12-21
        • 1970-01-01
        相关资源
        最近更新 更多