io - Go channels and I/O -
first function
readf2c
takes filename , channel, reads file , inputs in channel. second function
writec2f
takes 2 channels , filename, takes value of each channel , saves lower value in output file. i'm sure there few syntax errors i'm new go
package main import ( "fmt" "bufio" "os" "strconv" ) func main() { fmt.println("hello world!\n\n") cs1 := make (chan int) var nameinput string = "input.txt" readf2c(nameinput,cs1) cs2 := make (chan int) cs3 := make (chan int) cs2 <- 10 cs2 <- 16 cs2 <- 7 cs2 <- 2 cs2 <- 5 cs3 <- 8 cs3 <- 15 cs3 <- 14 cs3 <- 1 cs3 <- 6 var nameoutput string = "output.txt" writec2f (nameoutput,cs2,cs3) } func readf2c (fn string, ch chan int){ f,err := os.open(fn) r := bufio.newreader(f) err != nil { // not end of file fmt.println(r.readstring('\n')) ch <- r.readstring('\n') } if err != nil { fmt.println(r.readstring('\n')) ch <- -1 } } func writec2f(fn string, // output text file ch1 chan int, // first input channel ch2 chan int){ var j int = 0 var channel1temp int var channel2temp int f,_ := os.create(fn) w := bufio.newwriter(f) channel1temp = <-ch1 channel2temp = <-ch2 j := 1; j <= 5; j++ { if (channel2temp < channel1temp){ n4, err := w.writestring(strconv.itoa(channel1temp)) } else{ n4, err := w.writestring(strconv.itoa(channel2temp)) } w.flush() } }
this error messages get:
prog.go:38: multiple-value r.readstring() in single-value context prog.go:65: w.flush undefined (cannot refer unexported field or method bufio.(*writer)."".flush)
there multiple errors:
1)
unlike c, go enforces have curly braces directly after statements. if case (and same func), instead of doing this:
if (channel2temp < channel1temp) {
use this
if channel2temp < channel1temp {
2)
there no while
in go. use for
for { ... }
or
for channel1temp != null || channel2temp != null { ... }
3)
usage of non-declared variables. easy fix making short variable declaration first time initialize variable. instead of:
r = bufio.newreader(file)
use
r := bufio.newreader(file)
4)
trying assign multi-value return single variable. if function returns 2 values , need one, variable don't want can discarded assigning _
. instead of:
file := os.open(fn)
use
file, _ := os.open(fn)
but best practice catch error:
file, err := os.open(fn) if err != nil { panic(err) }
there more errors on top of this, maybe started. suggest reading effective go since explain many of things i've mentioned.
edit:
and there online sure. might new language, online material useful. below few used when learning go:
- effective go: document on how write idiomatic go code
- the go programming language tour: online tour of go interactive examples.
- go example: interactive examples of go programs, starting hello world.
- go specification: surprisingly readable being specification. maybe not start point, useful.
Comments
Post a Comment