Converting a custom type to string in Go

前端 未结 5 2080
感动是毒
感动是毒 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:15

    Better to define a String function for the Customtype - it can make your life easier over time - you have better control over things as and if the structure evolves. If you really need SomeFunction then let it return 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

提交回复
热议问题