golang / tour

[mirror] A Tour of Go
BSD 3-Clause "New" or "Revised" License
1.54k stars 519 forks source link

tour: Very Little Context or Clarity to Exercise (FYI: Solution Spoiler) #299

Open 4Z4T4R opened 6 years ago

4Z4T4R commented 6 years ago

Context: https://tour.golang.org/methods/22

As a newbie to Go, I have enjoyed the tutorials and exercises thusfar... until this exercise Re: Readers. I understand the syntax of methods, of return types, and method arguments, but in this sample exercise, I would not have deduced the solution based on the information given in the previous section. Specifically, I did not understand...

  1. ...that returning the length of the b byte array is necessitates a success condition for the reader.Validate method.
  2. ...that an infinite loop somehow equates to the use of a byte array with a range in the for loop. I was initially just expecting the read method to simply return an 'A' every time invoked.
  3. ...the explanation of the result... which I assume to be what I have commented below.

It feels like I just glossed over what could have been a little more detailed explanation of the design of the Read method, Reader interface, and the reader.Validate conditions. I wish I'd had more exposure to those concepts before resorting to googling for a solution to this exercise.

package main

import (
  "golang.org/x/tour/reader"
)

type MyReader struct{}

// TODO: Add a Read([]byte) (int, error) method to MyReader.

func (m MyReader) Read(b []byte) (int, error) {  // Why doesn't a pointer receiver work here?
    for i := range b {  // An arbitrary byte array is passed in.
        b[i] = 'A' // Set every index to 'A' in the byte array, but how is this validated? Assuming there's a m.Read(b) in Validate.
    }
    return len(b), nil // Emit the length of the resulting array as expected by the Reader interface.
}

func main() {
    reader.Validate(MyReader{})
}

Anyhow, I'm just sharing a noob's stream of consciousness here. I really want to understand Readers since I'm coming over from Node and looking forward to implementing a gRPC Go solution over HTTP/2 in lieu of Node's websockets protocols.

jonas-salomonsson commented 6 years ago

+1 I must say the description of this one gave a very different idea of what to do