gpt4 book ai didi

types - 如何将别名类型(成本)连接到 strings.Join()

转载 作者:IT王子 更新时间:2023-10-29 02:24:11 26 4
gpt4 key购买 nike

我有一个允许传入值片段的包/API。例如:

type ConstType string

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

注意这个类型是字符串的别名。

我遇到的我认为是非惯用步骤的地方是我无法将这种类型别名的一部分转换或推断为 []string slice 。

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, ",")
}

我把它放在 Playground 上来展示一个完整的例子:

http://play.golang.org/p/QMZ9DR5TVR

我知道 Go 的解决方案是将其转换为类型(显式类型转换,喜欢这个规则!)。我只是不知道如何在不遍历集合的情况下将类型的一部分转换为 []string。

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

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

播放:http://play.golang.org/p/839Qp2jmIz

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

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

最佳答案

正如@Not_a_Golfer 指出的那样,您确实应该遍历 constType slice 并构建一个新的 string slice 。这有复制每个元素的缺点(这对您来说可能重要也可能不重要)。

还有另一种解决方案,尽管它涉及标准库中的unsafe 包。我修改了您发布到 Go Playground 的示例(新链接是 http://play.golang.org/p/aLmvSraktF)

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

关于types - 如何将别名类型(成本)连接到 strings.Join(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27299180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com