go type-switch 如何处理 point to nil
go type-switch how to deal with point to nil
像这样,如果msg指向空值,如何在clean code
中处理
func test(a SomeType) {
switch msg := a.(type) {
case *type1:
dosomething1(a)
case *type2:
dosomething2(a)
case *type3:
dosomething3(a)
default:
do()
}
主要功能可能是这个
func main() {
var b_ptr *stTest
aa := interface{}(b)
test(aa)
}
type test struct {
c int
d string
}
b_ptr是一个指针,但是指向nil,我想在test func中判断
如果我在测试函数中使用 b_ptr,例如:打印 a.c 或 a.d,它将崩溃。
我是这样操作的。做if(),到处用a,但是太蠢了
func test(a SomeType) {
switch msg := a.(type) {
case *type1:
if msg == nil {
return
}
dosomething1(a)
case *type2:
if msg == nil {
return
}
dosomething2(a)
case *type3:
if msg == nil {
return
}
dosomething3(a)
default:
do()
}
通常这应该被认为是调用者的问题,因此处理后果应该是调用者的工作。传递包含 nil 值的非 nil 接口是不好的做法,除非它是 intentional/expected.
但是,如果您无法避免使用 nil 指针的非 nil 接口,那么您可以使用 reflect
来检查基础值是否为 nil
.
func test(a SomeType) {
if rv := reflect.ValueOf(a); !rv.IsValid() || rv.IsNil() {
return
}
switch msg := a.(type) {
case *type1:
dosomething1(a)
case *type2:
dosomething2(a)
case *type3:
dosomething3(a)
default:
do()
}
}
像这样,如果msg指向空值,如何在clean code
中处理func test(a SomeType) {
switch msg := a.(type) {
case *type1:
dosomething1(a)
case *type2:
dosomething2(a)
case *type3:
dosomething3(a)
default:
do()
}
主要功能可能是这个
func main() {
var b_ptr *stTest
aa := interface{}(b)
test(aa)
}
type test struct {
c int
d string
}
b_ptr是一个指针,但是指向nil,我想在test func中判断 如果我在测试函数中使用 b_ptr,例如:打印 a.c 或 a.d,它将崩溃。
我是这样操作的。做if(),到处用a,但是太蠢了
func test(a SomeType) {
switch msg := a.(type) {
case *type1:
if msg == nil {
return
}
dosomething1(a)
case *type2:
if msg == nil {
return
}
dosomething2(a)
case *type3:
if msg == nil {
return
}
dosomething3(a)
default:
do()
}
通常这应该被认为是调用者的问题,因此处理后果应该是调用者的工作。传递包含 nil 值的非 nil 接口是不好的做法,除非它是 intentional/expected.
但是,如果您无法避免使用 nil 指针的非 nil 接口,那么您可以使用 reflect
来检查基础值是否为 nil
.
func test(a SomeType) {
if rv := reflect.ValueOf(a); !rv.IsValid() || rv.IsNil() {
return
}
switch msg := a.(type) {
case *type1:
dosomething1(a)
case *type2:
dosomething2(a)
case *type3:
dosomething3(a)
default:
do()
}
}