go - Correct on input but panic on output in golang -
trying write bit of go, create sort of cat function in golang:
package main import ( "fmt" "os" "io/ioutil" "log" ) func main() { // part ask question , input fmt.print("which file read?: ") var input string fmt.scanln(&input) fmt.print(input) // part give output f, err := os.open(os.args[1]) // open file if err != nil { log.fatalln("my program broken") } defer f.close() // close things open bs, err := ioutil.readall(f) if err != nil { log.fatalln("my program broken") } // part print output fmt.printf("input", bs) // %s convert directly in string result } but go panic on execution , not find more explicit information.
what have done wrong?
how can more information error terminal?
$ go run gocat.go file read?: gocat.go gocat.gopanic: runtime error: index out of range
goroutine 1 [running]: panic(0x4b1840, 0xc42000a0e0) /usr/lib/go/src/runtime/panic.go:500 +0x1a1 main.main() /home/user/git/go-experimentations/gocat/gocat.go:23 +0x4ba exit status 2
i imagine found examples online , don't quite understand going on.
from os package's documentation.
args hold command-line arguments, starting program name.
since started program without arguments , os.args slice, program panics when access out of slice's bounds. (like trying access element of array not exist)
it looks trying prompt input here
var input string fmt.scanln(&input) fmt.print(input) all need replace
f, err := os.open(os.args[1]) with:
f, err := os.open(input) your last print statement incorrect.
it should be:
// part print output fmt.printf("input \n %s", string(bs)) you need cast bs []byte string , need add %s indicate fmt.printf string(bs) should placed in format string
Comments
Post a Comment