golang cannot assign to
Posted 翔云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang cannot assign to相关的知识,希望对你有一定的参考价值。
问题:
# command-line-arguments
.\example.go:22: cannot assign to m.V.(BasicMessage).Length
想在函数中修改interface表示的结构体的成员变量的值,编译时遇到这个编译错误,问题代码如下:
package main
import (
"fmt"
)
type Message struct {
V interface{}
}
type BasicMessage struct {
Length int
}
func test(m *Message) {
m.V.(BasicMessage).Length = 1
}
func main() {
m := &Message{}
fmt.Println("m:", m)
test(m)
fmt.Println("m:", m)
}
原因:
interface不能使用这种赋值方式。
解决办法:
将test函数中赋值方式修改为:
func test(m *Message) {
bm := BasicMessage{}
bm.Length = 1
m.V = bm
}
output:
m: &{<\nil>}
m: &{{1}}
以上是关于golang cannot assign to的主要内容,如果未能解决你的问题,请参考以下文章
重构改善既有代码设计--重构手法07:Remove Assignments to Parameters (移除对参数的赋值)
Flink producer attempted to use a producer id which is not currently assigned to its transaction(代码片
kafkaThe replication factor in manual replication assignment is not equal to the existing replica(代码
Vue报错:Uncaught TypeError: Cannot assign to read only property 'exports' of object 的解决方法(代码片段
错误提示:'……' is not assignable to Android.app.Activity Manifest XML
python三元运算符—报错“SyntaxError: can't assign to conditional expression”