我有一個包/ API允許傳入一段值。例如:如何將(const的)別名類型連接到strings.Join()
type ConstType string
const (
T_Option1 ConstType = "OPTION-1"
T_Option2 ConstType = "OPTION-2"
T_Option3 ConstType = "OPTION-3"
)
請注意此類型是字符串的別名。
當我遇到一個什麼 - 我 - 思考 - 是 - 非idomatic一步的是,我不能投或推斷該類型別名的片到片[]string
。
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, ",")
}
我在操場上把這個共同展示一個完整的例子:
http://play.golang.org/p/QMZ9DR5TVR
我知道圍棋的解決辦法是將它轉換爲類型(顯式類型轉換,愛情的規則!)。我只是無法弄清楚如何將一段類型轉換爲[]字符串 - 而無需循環收集。
一個我喜歡圍棋的原因是類型轉換的實施,如:
c := T_OPTION1
v := string(c)
fmt.Println(v)
播放:http://play.golang.org/p/839Qp2jmIz
雖然,我不能確定如何做到這一點在整個片不用循環。我必須循環嗎?
鑑於,循環收集並不是什麼大事,因爲最多隻能有5到7個選項。但是,我仍然覺得應該有一種可行的方式來做到這一點。
簡短的回答 - 你不能施放到另一種類型的切片的slace沒有通過它循環。 – 2014-12-04 16:40:11
那麼,這是我正在尋找的答案。發佈它以獲得標記! – eduncan911 2014-12-04 17:00:16