将一种字符串类型转换为另一种字符串类型

时间:2020-05-28 16:27:03

标签: go

我有两种字符串类型。我是将一个字符串转换为另一种字符串类型的字符串。这不起作用,并且在nextT = nextS分配上失败。为什么?它们都有基本的字符串类型。谢谢。

package main

import (
    "fmt"
    "reflect"
)

type TFirstType string
type TSecondType string

func main() {
    var firstT TFirstType 
    firstT = "asdf"

    var secondT = fmt.Sprintf("%s", firstT )

    nextS := secondT 
    fmt.Println(reflect.TypeOf(nextS))

    var nextT TSecondType 
    nextT = nextS
}

func (c TFirstType ) String() string {
    return string(c)
}

示例:https://play.golang.org/p/DwEY6hWacVA

1 个答案:

答案 0 :(得分:-1)

这不是很明显,我将不得不阅读更多内容来弄清楚.JimB,Adrian和Abu各自提供了帮助。这行得通...

package main

import (
    "fmt"
    "reflect"
)

type TFirstType string
type TSecondType string

func main() {
    var firstT TFirstType 
    firstT = "asdf"

    var secondT = fmt.Sprintf("%s", firstT )

    nextS := secondT 
    fmt.Println(reflect.TypeOf(nextS))

    var nextT TSecondType 
    nextT = TSecondType(nextS)
    fmt.Println(nextT)
}

func (c TFirstType ) String() string {
    return string(c)
}