问题
invalid operation: m[1] (type *string does not support indexing)
错误复现
func TestStringPtr(t *testing.T){
str := "this is a message"
m := &str
t.Log(*m[1])
}
// output
ouyangjun@:~/data/project/algorithm/leetcode/0010$go test -v -run="StringPtr"
# github.com/oyjjpp/algorithm/leetcode/0010 [github.com/oyjjpp/algorithm/leetcode/0010.test]
./0010_test.go:18:13: invalid operation: m[1] (type *string does not support indexing)
FAIL github.com/oyjjpp/algorithm/leetcode/0010 [build failed]
原因
写代码第一印象str为“string”类型,m为“prt”类型,通过验证确实如理解所示
func TestStringPtr(t *testing.T){
str := "this is a message"
m := &str
t.Log(reflect.ValueOf(m).Kind())
t.Log(reflect.ValueOf(*m).Kind())
}
// output
=== RUN TestStringPtr
0010_test.go:18: ptr
0010_test.go:19: string
--- PASS: TestStringPtr (0.00s)
PASS
但是输出结果却与理解不同,再去读一遍错误信息“invalid operation: m[1] (type *string does not support indexing” 很明显的错误啊,类型错误,”*m“明明是字符串类型啊,为什么不对呢?
重点,重点,重点 [关键点“m[1]” 操作符的优先级]
第一印象以为*m[1] m指针先转换为string再取值,实际是先通过m去取值,在转指针,所以报列上面错误
解决方案
使用“()”,改变优先级
func TestStringPtr(t *testing.T){
str := "this is a message"
m := &str
t.Log(reflect.ValueOf(m).Kind())
t.Log(reflect.ValueOf(*m).Kind())
t.Log((*m)[1])
}