2014-12-04 20 views
1

我有一個包/ 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個選項。但是,我仍然覺得應該有一種可行的方式來做到這一點。

+0

簡短的回答 - 你不能施放到另一種類型的切片的slace沒有通過它循環。 – 2014-12-04 16:40:11

+0

那麼,這是我正在尋找的答案。發佈它以獲得標記! – eduncan911 2014-12-04 17:00:16

回答

0

正如@Not_a_Golfer所指出的那樣,你應該真的在循環切入constType並建立一個新的string切片。這具有複製每個元素的缺點(對你而言可能並不重要)。

還有另一種解決方案,雖然它涉及標準庫中的unsafe包。我修改你發佈到去遊樂場(新鏈接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()) 
} 
+0

哈,不安全!是的,我只是看到如果我錯過了一些鑄造的東西。我現在看到,循環或不安全。稍微調整一下你的代碼:'fmt.Println(types.String())'得到想要的結果。奇怪的是,我認爲Println會調用String()。 +1 – eduncan911 2014-12-04 21:12:56

+0

@PeterStace:注意:「Package unsafe包含圍繞Go程序類型安全的操作,導入不安全的程序包可能不可移植,並且不受Go 1兼容性準則的保護。」 – peterSO 2014-12-05 03:26:15