Josh Weinstein
Josh Weinstein

Reputation: 2968

println turning up as empty string in go

So I wrote this small go program, that gives instructions to a turing machine, and prints selected cells from it:

    package main

import "fmt"
import s "strings"

func main() {
  fmt.Println(processturing("> > > + + + . ."));
}

func processturing(arguments string) string{
    result := ""
    dial := 0
    cells := make([]int, 30000)
    commands := splitstr(arguments, " ")
    for i := 0;i<len(commands);i++ {
        switch commands[i] {
        case ">":
            dial += 1
        case "<":
            dial -= 1
        case "+":
            cells[dial] += 1
        case "-":
            cells[dial] -= 1
        case ".":
            result += string(cells[dial]) + " "
        }
    }
    return result
}

//splits strings be a delimeter
func splitstr(input, delim string) []string{
    return s.Split(input, delim)
}

Problem is, when this is run, the console doesn't display anything. It just displays nothing. How do I make this work to fmt.println the resulting string from my function?

Upvotes: 0

Views: 279

Answers (1)

Thundercat
Thundercat

Reputation: 120951

The expression

 string(cells[dial])

yields the UTF-8 representation of the integer value cells[dial]. Print the quoted string output to see what's going on:

    fmt.Printf("%q\n", processturing("> > > + + + . .")) // prints "\x03 \x03 "

I think you want the decimal representation of the integer:

 strconv.Itoa(cells[dial])

playground example.

Upvotes: 6

Related Questions