示例:
import (
"fmt"
)
func main() {
var v = ""
fmt.Println(isEmptyString(&v))
}
func isEmptyString(val interface{}) bool {
// lets say we know it is string and don't need to check
// how to dereference val into string value so we can do value == "" ????
}
正常的 deRef * 不起作用,尝试使用反射包..没有运气
您需要的代码是这样的:
package main
import (
"fmt"
)
func main() {
var v = ""
fmt.Println(isEmptyString(&v))
}
func isEmptyString(val interface{}) (bool, error) {
switch v := val.(type) {
case *string:
str := *v
if str == "" {
return true, nil
}
return false, nil
default:
return false, fmt.Errorf("the value is not string pointer")
}
}
既然你说你知道它是字符串并且不需要检查,你可以这样:
import (
"fmt"
)
func main() {
var v = ""
fmt.Println(isEmptyString(&v))
}
func isEmptyString(val interface{}) bool {
return *val.(*string) == ""
}