Home > database >  ReadAll not declared by package iocompiler - Golang
ReadAll not declared by package iocompiler - Golang

Time:06-01

I am using golang in my project.

The code is as follows

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "sync"
    "time"

)

....
if response.StatusCode != 200 {
        respBdy, _ := io.ReadAll(response.Body)
        return fmt.Errorf("%v response from client: %v", response.StatusCode, respBdy)
    }

When i run the project using make run, i am getting the following error

[email protected]/messengers/client.go:133:17: undefined: io.ReadAll

On debugging, i can understand the problem is ReadAll not declared by package iocompiler

Any idea on how to fix this?

Edit: The go version i am using is

go version
go version go1.15.6 darwin/amd64

CodePudding user response:

As Manjeet and Emile stated, starting from go1.16's release, the functions from io/ioutil are moved to io package.

Discard => io.Discard
NopCloser => io.NopCloser
ReadAll => io.ReadAll
ReadDir => os.ReadDir
ReadFile => os.ReadFile
TempDir => os.MkdirTemp
TempFile => os.CreateTemp
WriteFile => os.WriteFile

Linking release notes of go1.16 for reference.

About the mismatch of go versions: go1.13 in go.mod and go1.15 in terminal, the go version in go.mod gets added depending on the version when it was initialised using go mod init [module-path]. GoDoc page for go mod init doesn't clear your doubt but attaching for ref.

In other words, the go.mod doesn't denote your local go version. Rather, it gives the minimal go version and imported package's versions that will let your project (as module) run hassle-free.

I found a sample from an old project. Will try to explain on it.

module project-name

go 1.14

require (
    github.com/go-redis/redis/v7 v7.4.0
    github.com/stretchr/testify v1.6.1
    github.com/vektra/mockery v1.1.2 // indirect
)

This means the project requires go1.14, along with [email protected], [email protected] and [email protected] at the very least. Lower than these versions "might" still work. Not recommended. Higher than those versions are expected to be better, but there is a possibility of change of names or package name like above. More details at gomod-ref.

Just another bit of info: the io and io/util are part of Go's standard library. This means that in order to use the function as io.ReadAll, you would need higher version of standard library, and so, higher version of Go (1.16 at least).

Conclusion: You can still keep go1.13 in go.mod. Just upgrade the go version in local. And if other devs are kind enough to let you upgrade in go.mod too, do it!

Opinion: I personally recommend go1.17's latest for now until all external packages implement go1.18 and generics.

  •  Tags:  
  • go
  • Related