Converting a custom type to string in Go

前端 未结 5 2071
感动是毒
感动是毒 2020-12-14 15:36

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

type CustomType string

const (
        Foobar CustomType = \"somestr         


        
5条回答
  •  执笔经年
    2020-12-14 16:31

    For every type T, there is a corresponding conversion operation T(x) that converts the value x to type T. A conversion from one type to another is allowed if both have the same underlying type, or if both are unnamed pointer types that point to variables of the same underlying type; these conversions change the type but not the representation of the value. If x is assignable to T, a conversion is permitted but is usually redundant. - Taken from The Go Programming Language - by Alan A. A. Donovan

    As per your example here are some of the different examples which will return the value.

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

    It will output:

    somestring
    somestring
    somestring
    

    The Go Playground link

提交回复
热议问题