难以理解一段golang代码 [英] Have trouble understanding a piece of golang code

查看:132
本文介绍了难以理解一段golang代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package main

type Writeable interface {
    OnWrite() interface{}
}

type Result struct {
    Message string
}

func (r *Result) OnWrite() interface{} {
    return r.Message
}

// what does this line mean? what is the purpose?
var _ Writeable = (*Result)(nil)


func main() {

}

代码段中的注释表达了我的困惑. 据我了解,带有注释的行通知编译器检查结构是否实现了该接口,但是我不太确定.有人可以帮忙解释一下目的吗?

The comments in the code snippet expressed my confusion. As I understood, the line with comment notifies the compiler to check whether a struct has implemented the interface, but I am not sure very much. Could someone help explaining the purpose?

推荐答案

正如您所说,这是一种验证Result实现Writeable的方法.从 GO常见问题解答:

As you say it's a way to verify that Result implements Writeable. From the GO FAQ:

您可以要求编译器检查T类型是否实现了 通过尝试分配来界面I:

You can ask the compiler to check that the type T implements the interface I by attempting an assignment:

type T struct{} 
var _ I = T{}   // Verify that T implements I.

空白标识符_代表此处不需要的变量名(从而防止出现已声明但未使用"错误).

The blank identifier _ stands for the variable name which is not needed here (and thus prevents a "declared but not used" error).

(*Result)(nil)通过转换 nilResult的值的未初始​​化指针>.这样可以避免像new(Result)&Result{}那样为空结构分配内存.

(*Result)(nil) creates an uninitialized pointer to a value of type Result by converting nil to *Result. This avoids allocation of memory for an empty struct as you'd get with new(Result) or &Result{}.

这篇关于难以理解一段golang代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆