duanniedang3946 2018-01-26 11:46
浏览 58
已采纳

为什么为涉及指针的类型定义将指针分配给指针是非法的?

I have the following code:

package main

type Vertex struct {
    X, Y float64
}

type VertexPointer *Vertex

func main() {
    v := Vertex{3, 4}
    v_ptr := &v

    var test_1 *Vertex = &v
    var test_2 **Vertex = &v_ptr

    var test_3 VertexPointer = &v
    var test_4 *VertexPointer = &v_ptr
}

When I try and run it (I'm using Go 1.6.2) I get the following error:

# command-line-arguments
./pointers.go:17: cannot use &v_ptr (type **Vertex) as type *VertexPointer in assignment

I'm confused why the assignment involving test_3works but not test_4. Based on what I've been reading, my understanding is that either both assignments should work or neither of them should work. Isn't the described behaviour a bit inconsistent?

  • 写回答

1条回答 默认 最新

  • dongtang8678 2018-01-26 11:50
    关注

    This is all "governed" by Spec: Assignability. Assigning to test_3 is covered by this:

    A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

    And none of the assignability rules cover test_4, so it's not allowed.

    The underlying type is detailed in Spec: Types:

    Each type T has an underlying type: If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration.

    In case of test_3:

    var test_3 VertexPointer = &v
    

    Type of test_3 is VertexPointer (explicitly specified), type of &v is *Vertex. Underlying type for both are *Vertex, and type of &v (which is *Vertex) is an unnamed type, so the assignment is OK. Vertex is a named type, but derived types such as *Vertex or []Vertex are unnamed types.

    In case of test_4:

    var test_4 *VertexPointer = &v_ptr
    

    Type of test_4 is *VertexPointer, type of &v_ptr is **Vertex because type of v_ptr is *Vertex, not VertexPointer. Underlying type of test_4 is *VertexPoitner, underlying type of &v_ptr is **Vertex. The underlying types do not match. So there is no assignability rule that applies, so this assignment is not OK.

    See similar question: Custom type passed to function as a parameter

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

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真