In short, attached is my code. Any advice on how to make it simpler or better would be appreciated.
--Joey
Why do you feel this is a "ridiculous amount of imports"? Seems
reasonable to me.
You could definitely split parts of this function up into separate
functions. The part that handles hello.in is a good candidate.
> func walk(root string) filepath.WalkFunc {
> count := 0
> return func(path string, info os.FileInfo, err error) error {
> if info.IsDir() {
> if path == root {
> return nil
> }
> return filepath.SkipDir
> }
>
> if path == root+"/hello.in" {
> file, err := os.Open(path)
> if err != nil {
> return err
> }
>
> reader := bufio.NewReader(file)
>
> output, err := os.Create(root + "/hello.out")
> if err != nil {
> return err
> }
>
> var (
> isPrefix bool
> line []byte
> )
> for err == nil {
> line, isPrefix, err = reader.ReadLine()
You should check this error here, line may be something arbitrary if err != nil.
> file, err := os.Open(path)
> if err != nil {
> return err
> }
It is more common to follow this kind of code with an immediate "defer
file.Close()", rather than doing it after everything. In fact, your
code is omitting to close the file in any of the error cases, which a
defer would solve.
> if strings.Contains(string(line), "you") {
> fmt.Println(string(line))
> }
I'd use bytes.Contains instead of doing string conversions.
Other than those two things, it looks reasonable to me.
Dave.
> if strings.Contains(string(line), "you") {I'd use bytes.Contains instead of doing string conversions.
> fmt.Println(string(line))
> }
> if bytes.Contains(line, []byte("you")) {
> fmt.Println(string(line))
> }
>
> The print still needs line to be converted to a string so that I don't get
> an array of ascii codes, right?
Yeah, or you could write the bytes directly.
os.Stdout.Write(line)
os.Stdout.Write([]byte{'\n'})
but converting there is fine.
Dave.
On Mar 13, 2012 6:58 PM, "DisposaBoy" <dispo...@dby.me> wrote:
> no, fmt.Printf("%s\n", line) should do it
Yeah, that works too. I don't think it's quite as efficient, though.
Dave.