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 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果