Web/GoLang
[golang]Go에서 리플렉션을 통해 빈 값을 빠르게 감지하는 방법
벨포트조던
2022. 5. 24. 10:37
반응형
나는 int/ string/ bool/etc.. 값이 에 저장되어 있고 interface{}초기화되지 않았는지 확인하고 싶습니다. 즉, 다음 중 하나의 값이 있음을 의미합니다.
- 0
- ""
- false
- 또는nil
어떻게 확인합니까?
func IsZeroOfUnderlyingType(x interface{}) bool {
return reflect.DeepEqual(x, reflect.Zero(reflect.TypeOf(x)).Interface())
}
내 사용예
list := structs.Map(q)
column := []string{"aaa", "bbb", "ccc", "ddd"}
for key, val := range list {
if !(contains(column, key) && !IsZeroOfUnderlyingType(val)) {
delete(list, key)
}else{
fmt.Println("Key:", key, "=>", "val:", val)
}
필요한 컬럼 이외에는 삭제하는 작업시 사용함
https://stackoverflow.com/questions/13901819/quick-way-to-detect-empty-values-via-reflection-in-go
Quick way to detect empty values via reflection in Go
I have a int/string/bool/etc.. value stored in an interface{} and want to determine if it's uninitialized, meaning that it has a value of either 0 "" false or nil How do I check this?
stackoverflow.com
반응형