douyeyan0650 2017-05-03 02:10
浏览 68
已采纳

返回接口时的类型断言

I'm new to golang; however based on my current knowledge I understand that a value-type and a reference-type can both fulfill an interface. But it seems in regards to type assertion, how you return a struct does matter. See the following:

package main

import (
    "fmt"
)

type SomeError interface {
    Error() string
}

type ConcreteError struct{}

func (ConcreteError) Error() string {
    return "?"
}

func returnPointer() SomeError {
    return &ConcreteError{}
}

func returnVal() SomeError {
    return ConcreteError{}
}

func main() {
    pointer := returnPointer()
    value := returnVal()
    _, pointerWithPointer := pointer.(*ConcreteError);
    _, pointerWithValue := pointer.(ConcreteError);

    _, valueWithValue := value.(ConcreteError);
    _, valueWithPointer := value.(*ConcreteError)

    fmt.Printf("Returning a pointer, assert using (*ConcreteError): %v
", pointerWithPointer); // true
    fmt.Printf("Returning a pointer, assert using (ConcreteError): %v
", pointerWithValue); // false
    fmt.Printf("Returning a value,   assert using (ConcreteError): %v
", valueWithValue); // true
    fmt.Printf("Returning a value,   assert using (*ConcreteError): %v
", valueWithPointer); // false
}

So if my understanding is correct, the user needs to know how the struct is returned to correctly assert its type?

I'm going to guess and assume the standard practice in golang is to always return a pointer to a struct(i.e like *PathError)?

link to play: here

  • 写回答

1条回答 默认 最新

  • duanhemou9834 2017-05-03 02:14
    关注

    So if my understanding is correct, the user needs to know how the struct is returned to correctly assert its type?

    It depends. If you need the type assertion to pass - you surely need to know the exact type of the value. a and *a are different types.

    I'm going to guess and assume the standard practice in golang is to always return a pointer to a struct(i.e like *PathError)?

    No.

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

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重