dsfsdf7852 2014-09-07 20:01 采纳率: 100%
浏览 56
已采纳

前往:在结构上输入断言?

package main

import "fmt"

type Number int

func (n *Number) IncreaseMe(i int) {
        *n += i
}

func main() {
        n := Number(10)

        n.IncreaseMe(90) // n is now supposed to be 100

        fmt.Println(n)
}

When running the code above, it gives me the error message

invalid operation: *n += i (mismatched types Number and int)

Which is to be expected as it's trying to do a math operation on variables which don't share the same type.

I then tried

*n.(int) += i

which tells the compiler not to worry as *n can be safely treated as an integer, which leads me to

invalid type assertion: n.(int) (non-interface type *Number on left)

I believe this is happening because type assertions works only with interfaces, not custom types.

So what is the solution for this?

  • 写回答

1条回答 默认 最新

  • donglu0494 2014-09-07 20:05
    关注

    As mentioned in "Go: Named type assertions and conversions"

    Type assertion works for interfaces only. Interface can have arbitrary underlying type, so we have type assertion and type switch to the rescue.

    You don't need type assertion: you can just:

    • convert *n to an int: int(*n) (since you know full well the actual type).
    • make the addition
    • convert back to Number

      *n = Number(int(*n) + i)
      

    See this <kbd>play.golang.org</kbd>: the output is 100.


    As ruakh mentions in the comments:

    Go splits the concept of "casting" into two separate concepts:

    • one ("type conversions") for conversions that the compiler knows are correct, and
    • one ("type assertions") for conversions that must be checked at runtime.

    The latter only applies to interfaces, since only interfaces have additional type information at runtime that that's not known at compile time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。