Why does the function return data?


(cinematik) #1

https://play.golang.org/p/WhslChgdMQB

package main

import (
	"fmt"
	"io"
)

type phoneReader string

func (ph phoneReader) Read(p []byte) (int, error) {
	count := 0
	for i := 0; i < len(ph); i++ {
		if ph[i] >= '0' && ph[i] <= '9' {
			p[count] = ph[i]
			count++
		}
	}
	return count, io.EOF
}

func main() {
	phone1 := phoneReader("+1(234)567 9010")
	buffer := make([]byte, len(phone1))
	phone1.Read(buffer)
	fmt.Println(string(buffer)) // 12345679010
}

I’m I understand it right that in line 24 the buffer variable is the source of data for function Read and after the function completed the buffer is also recieves the result?

The reciver is phone1 & the buffer we pass as a container, but the Read function returns (int, error), so why that function returns those two variables if the following code don’t use them?

If function make creates not a reference (or reference?), then we pass into Read function a copy of buffer, so how in this case the buffer outside the function is updated?


(Yamil Bracho) #2
  1. You can ignore function’s results if it is the case
  2. In your case, make creates a slice and slie is a struct that contains a pointer to the area
    where data will be readen/written. Check https://golang.org/doc/effective_go.html#allocation_make