doujing2497
2016-02-28 01:35
浏览 16
已采纳

是否导出嵌入式错误?

According to the Go language spec, I can embed a type in a struct.

There is a weird case with the error interface. It is not uppercased, so I assume it is not exported as a type. But it is defined by the language. So if I have a struct like this:

package foo

type Err struct {
    error
}

is the embedded error exported? Does Err satisfy the error interface?

Can I access it from another package, i.e. is the following ok?

package main

import "errors"
import "fmt"
import "foo"

func main() {
    e := foo.Err{}
    e.error = errors.New("Hello world!") // is this okay?
    fmt.Println(e.Error())
}

图片转代码服务由CSDN问答提供 功能建议

根据 Go语言规范,我可以将类型嵌入结构体中。

error 接口有一个奇怪的情况。 它不是大写的,所以我假设它没有作为类型导出。 但是它是由语言定义的。 因此,如果我有这样的结构:

  package foo 
 
type Err struct {
 error 
} 
   
  
 

是否导出了嵌入式 error Err 是否满足 error 接口的要求?

我可以从其他软件包中访问它吗,即可以吗?

 包main 
 
import“ errors” 
import“ fmt” 
import“ foo” 
 
func main(){
e:= foo.Err {} 
 e。 错误= errors.New(“ Hello world!”)//可以吗?
 fmt.Println(e.Error())
} 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzhiju0324 2016-02-28 02:25
    已采纳

    When you embed an error interface into a struct, basically, you add a field named error with type error to it.

    Because it's embedded your struct now also implements all of it's methods. That means your struct satisfies the error interface and you can call Error() on it or just pass it to Println as it is and it will type assert it into error and call Error() for you https://play.golang.org/p/0VxUUX2l-z

    Obviously, because field is named error it's not exported. But the struct still satisfies the error interface because it has Error() method.

    Interesting consequence of this is that if you don't initialize the field Println will panic because it will try to call Error() on nil https://play.golang.org/p/XctFgKZI-K

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题