Types 如何将别名类型(常量)连接到字符串中。Join()

Types 如何将别名类型(常量)连接到字符串中。Join(),types,casting,go,alias,Types,Casting,Go,Alias,我有一个包/API,它允许传入一部分值。例如: type ConstType string const ( T_Option1 ConstType = "OPTION-1" T_Option2 ConstType = "OPTION-2" T_Option3 ConstType = "OPTION-3" ) 请注意,此类型是字符串的别名 我遇到了一个我认为是非idomatic的步骤,那就是我无法将这种类型的片段转换或推断为[]字符串片段。 type constType

我有一个包/API,它允许传入一部分值。例如:

type ConstType string

const (
    T_Option1 ConstType = "OPTION-1"
    T_Option2 ConstType = "OPTION-2"
    T_Option3 ConstType = "OPTION-3"
)
请注意,此类型是字符串的别名

我遇到了一个我认为是非idomatic的步骤,那就是我无法将这种类型的片段转换或推断为
[]字符串
片段。

type constTypes struct {
    types []ConstType
}

func (s *constTypes) SetConstTypes(types []ConstType) {
    s.types = types
}

func (s *constTypes) String() string {

    // this generates a compile error because []ConstType is not
    // and []string.
    //
    // but, as you can see, ConstType is of type string
    //
    return strings.Join(s.types, ",")
}
我把这些放在操场上展示了一个完整的例子:

我知道Go的解决方案是将其转换为类型(显式类型转换,喜欢这个规则!)。我只是不知道如何将类型片段强制转换为[]字符串,而不在集合中循环

我喜欢Go的原因之一是强制执行类型转换,例如:

c := T_OPTION1
v := string(c)
fmt.Println(v)
播放:

不过,我不确定如何在不循环的情况下跨切片执行此操作。我必须循环吗


鉴于此,在集合中循环不是什么大问题,因为最多只能设置5到7个选项。但是,我仍然觉得应该有一种可转换的方法来做到这一点。

正如@Not_a_Golfer所指出的,你真的应该在
constType
的片段中循环,并构建一个新的
string
片段。这样做的缺点是复制每个元素(这可能对您来说很重要,也可能不重要)

还有另一种解决方案,尽管它涉及标准库中的
不安全
包。我已经修改了您发布到Go游乐场的示例(新链接为)


简短的回答-你不能在不循环的情况下将一种类型的slace转换为另一种类型的slace。好吧,这就是我要寻找的答案。把它贴出来做标记!哈,不安全!是的,我只是想看看我是否错过了一些演员。我现在明白了,循环还是不安全。对代码稍加修改:
fmt.Println(types.String())
以获得所需的结果。奇怪的是,我以为Println会调用String()+1@PeterStace:注意:“包不安全包含绕过Go程序类型安全的操作。导入不安全的包可能不可移植,并且不受Go 1兼容性指南的保护。”
package main

import (
    "fmt"
    "strings"
    "unsafe"
)

type ConstType string

const (
    T_Option1 ConstType = "OPTION-1"
    T_Option2 ConstType = "OPTION-2"
    T_Option3 ConstType = "OPTION-3"
)

// constTypes is an internal/private member handling
type constTypes struct {
    types []ConstType
}

func (s *constTypes) SetConstTypes(types []ConstType) {
    s.types = types
}

func (s *constTypes) String() string {

    // Convert s.types to a string slice.
    var stringTypes []string // Long varibale declaration style so that you can see the type of stringTypes.
    stringTypes = *(*[]string)(unsafe.Pointer(&s.types))

    // Now you can use the strings package.
    return strings.Join(stringTypes, ",")
}

func main() {

    types := constTypes{}

    // a public method on my package's api allows this to be set via a slice:
    types.SetConstTypes([]ConstType{T_Option1, T_Option2, T_Option3})

    fmt.Println(types.String())
}