doudong7256 2014-03-27 16:13
浏览 1187
已采纳

星号(* 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  }

When I use os.Open to open a file

dictFile, err := os.Open(file)

I'm going to pass dicFile to

reader := bufio.NewReader(dictFile)

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?

  • 写回答

2条回答 默认 最新

  • dongzai3139 2014-03-27 16:25
    关注

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

    This is called a type assertion:

    b, ok := rd.(*Reader)
    

    From golang spec:

    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.

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。