2012-12-31 105 views
2

這是一個包含一些常量的包。如何使用反射按名稱獲取包常量值?

package object 

type Languaege int 

const (
    Javascript Languaege = iota 
    C 
    Cpp 
    Shell 
) 

// ========================================

如果我知道它的名字,我怎樣才能得到一個類型語言的值?

package main 
func GetConstByName(name String) { 
    .... 
} 
lang := GetConstByName("Shell") 

回答

3

我不認爲你可以這樣做,除非你想要Language保持const整數類型。

這是我會做 - 讓語言工具Stringer這意味着你可以打印它。然後,您可以反轉languageMap把語言字符串爲Language

Playground link

package main 

import "fmt" 

type Language int 

const (
    Javascript Language = iota 
    C 
    Cpp 
    Shell 
) 

var languageMap = map[Language]string{ 
    Javascript: "Javascript", 
    C:   "C", 
    Cpp:  "Cpp", 
    Shell:  "Shell", 
} 

func (l Language) String() string { 
    return languageMap[l] 
} 

var languageMapReverse map[string]Language 

func NewLanguage(languageName string) Language { 
    if languageMapReverse == nil { 
     languageMapReverse = make(map[string]Language) 
     for l, name := range languageMap { 
      languageMapReverse[name] = l 
     } 
    } 
    return languageMapReverse[languageName] 
} 

func main() { 
    fmt.Printf("C is %d: %s: %d\n", C, C, NewLanguage("C")) 
    fmt.Printf("Shell is %d: %s: %d\n", Shell, Shell, NewLanguage("Shell")) 
} 

此輸出

C is 1: C: 1 
Shell is 3: Shell: 3 
1

您正試圖濫用反射。在這種情況下,幸運的是,它不會工作。如果要映射到某些關聯值的字符串鍵,請改爲使用map[string]someValueType