星号(* struct)表示法在golang中是什么意思 [英] What does asterisk (*struct) notation mean in golang

查看:754
本文介绍了星号(* struct)表示法在golang中是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// NewReaderSize returns a new Reader whose buffer has at least the specified
43  // size. If the argument io.Reader is already a Reader with large enough
44  // size, it returns the underlying Reader.
45  func NewReaderSize(rd io.Reader, size int) *Reader {
46      // Is it already a Reader?
47      b, ok := rd.(*Reader)
48      if ok && len(b.buf) >= size {
49          return b
50      }
51      if size < minReadBufferSize {
52          size = minReadBufferSize
53      }
54      r := new(Reader)
55      r.reset(make([]byte, size), rd)
56      return r
57  }

当我使用os.Open打开文件时

When I use os.Open to open a file

dictFile, err := os.Open(file)

我将把dicFile传递给

I'm going to pass dicFile to

reader := bufio.NewReader(dictFile)

我发现底层代码正在使用func NewReaderSize ,但是我不明白的是 rd.(* Reader). Reader 是包 bufio 中包含的结构类型.我看到的后跟一个结构的星号是从指针 Reader 获取值的,但是它不是指针,因此没有任何意义.此外,它使用点运算符 rd.(* Reader),我完全感到困惑.第47行中的这种用法是什么意思?这是一种什么样的符号?

I found the underlying code is using func NewReaderSize, but what I can not understand is rd.(*Reader). Reader is the struct type contained in package bufio. Asterisk followed by a struct is from what I see to get the value from pointer Reader, but it is not a pointer, so it does not make sense. Further more, it's using dot operator rd.(*Reader), I totally got confused. What's the meaning of this kind of usage in line 47? What kind of notation it is?

推荐答案

newReaderSize 获取阅读器( io.Reader 接口)并返回指向 Reader的指针(在 bufio 中定义的 struct ).

newReaderSize takes a reader (io.Reader interface) and returns a pointer to Reader (struct defined in bufio).

这称为类型断言:

b, ok := rd.(*Reader)

根据golang规范:

From golang spec:

对于接口类型为T且类型为T的表达式x,主要表达式 x.(T)断言x不为nil,并且存储的值x中的T是类型T.符号x.(T)称为类型断言.

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

这行代码将读取器并认为它是 * Reader 的一种,如果成功,并且 Reader 具有足够大的缓冲区,可以立即返回(因为它已经我们想要的.)

This line is taking that reader and asserting it is a type of *Reader, if it succeeds and that Reader has buffer big enough its immedietly returned (because it's already what we want).

这篇关于星号(* struct)表示法在golang中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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