doushi7819 2014-09-27 04:04
浏览 50
已采纳

确定var是否为自定义类型

How to determine if the var passed to my Func is actually the Type that i want?

i have a custom Type

type Name string

and a bunch of constants of that type

const Fred Name = "fred"

and i have a func that i need to forbid any other type of input other than my custom Type ex:

func MyFunc(name1 Name, name2 Name) (*Person, error) {
//bunch of stuff
}

how i check inside my func that name1 and name2 are not strings passed to the func but exclusively the const i already defined in my type ex:

p, err := MyFunc(Fred,Albert) //What i want
p, err := MyFunc("fred","albert") //What i dont want to happen

if cannot answer my question how i can make like a Enum in Golang a type that means something and restrict other ppl to use that type i defined

  • 写回答

2条回答 默认 最新

  • douzhang2092 2014-09-27 04:23
    关注

    Short version? you can't create that restricting kind of enum.

    Long version, there are few options:

    Define a validation function on the "type":

    func (n Name) valid() bool { //private method
        switch n {
        case Mal, Kaylee: //all the valid constants
            return true
        }
        return false
    }
    

    This however doesn't stop someone from using Name("fred").valid() like @peterSO pointed out.

    Use a struct with a private member in it, however they aren't "constants" per-se, an outside package can reassign them to invalid values:

    type Name struct {
        n string
    }
    
    var (
        invalid = Name{}
        Mal     = Name{"mal"}
        Kaylee  = Name{"kaylee"}
    )
    
    func MyFunc(name1 Name, name2 Name) error {
        if name1 == invalid || name2 == invalid {
            return errors.New("invalid names")
        }
        return nil
    }
    

    Use numeric constants and a private array, this is the only fool-proof version really and the closest you will get to a real enum:

    type Name uint8
    
    var names = [...]string{
        "Mal",
        "Kaylee",
    }
    
    func (n Name) valid() bool {
        return uint8(n) < uint8(len(names))
    }
    
    func (n Name) String() string {
        if !n.valid() {
            return "invalid"
        }
        return names[n]
    } 
    
    const (
        Mal Name = iota
        Kaylee
    )
    
    func MyFunc(name1 Name, name2 Name) error {
        if !name1.valid() || !name2.valid() {
            return errors.New("invalid names")
        }
        return nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题