2021年4月3日 星期六

Golang tag

 Golang struct 可使用 tag。

內建tag:

json:json.Marshal / json.Unmarsh 使用

type Item struct{

    Price int `json:"price"`    //field name will be marshal / unmarshal to price 

}


自訂tag:

可用來擴充 struct field 資料,設定預設值。

type Item struct{

    Price int `json:"price" default:"10"`

}

func (I *item) GetPrice() int {

v := reflect.ValueOf(*I)
        tag := v.Type().Field(0).Tag.Get("default")

        if tag != "" {

i,_:= strconv.Atoi(tag)
            return i
        }

        return -1

}

可用來判斷合法值。

type Item struct{

    Price int `json:"valid" :"10-100"`

}

func (I *Item)GetDefaultPrice()int{

      v:=reflect.ValueOf(I)

       tag:=v.Type().Field(0).Tag.Get("valid")

        if tag!=""{
            val,_:=strconv.Atoi(tag)
            result:=strings.Split(tag,"-")    
            min,_:=strconv.Atoi(result[0])
            max,_:=strconv.Atoi(result[1])

             if val>=min && val<=max{
                return true
            }
                return false

         }
         return false
}


沒有留言:

張貼留言