I am sort of new to golang, and also kind of new to programming. And go has been very hard for me. This is one thing that always confuses me: data types. If you run this(not on the playground) then it will spit out:
./main.go:40: cannot use recorded (type string) as type SVC in append
and if I reverse the values in the append call, it will spit out:
./main.go:40: first argument to append must be slice; have string
What I am trying to do is grab all of the stuff in the home directory, append all of the values with the modifications to an array, then put the array into a file using ioutil. All I want(as of now) is to append the values to the slice in func record. Can anybody help?
package main
import "os"
import "io/ioutil"
import "fmt"
type SVC struct {
key string
val string
}
func main() {
os.Chdir("../../../../../../..")
var data, err = ioutil.ReadDir("home")
checkerr(err)
for _, data := range data {
fmt.Println(data.Name())
}
os.Chdir("home/beanboybunny/repos/bux/go/src/bux")
}
func checkerr(err1 error) {
if err1 != nil {
fmt.Println("error")
}
}
func writer(dataname string) {
f := "var "
uname := dataname
q := " = VVC{
"
w := " bux: 1,
"
e := " op: true,
"
c := "}"
b2 := f + uname + q + w + e + c
record(b2)
}
func record(recorded string) {
cache := []SVC{}
record SVC := recorded
appenda := append(cache, recorded)
}
Your type SVC struct
has two private string fields. If you just want an array of strings you don't need the SVC
type.
If you're just trying to build an array of strings with your specially formatted transform of the items in the home directory, here is a start showing the use of append and format strings: https://play.golang.org/p/eUKTKRxwfp
package main
import (
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
os.Chdir("../../../../../../..")
var data, err = ioutil.ReadDir("home")
checkerr(err)
lines := []string{}
for _, data := range data {
fmt.Println(data.Name())
lines = append(lines, buildLine(data.Name()))
}
fmt.Println(strings.Join(lines, "
"))
os.Chdir("home/beanboybunny/repos/bux/go/src/bux")
}
func checkerr(err1 error) {
if err1 != nil {
fmt.Printf("error: %v", err1)
}
}
func buildLine(dataname string) string {
return fmt.Sprintf("var %s = VVC{
bux: 1,
op: true,
}", dataname)
}
You can not add meters to liters. So you can't append string
type to a list of SVC
records.
If you want []SVC
as output (list of SVC
) you need to implement a parser that transform a string to an SVC
object and append it.
If you want []string
as output you need to implement a serializer that transform an SVC
to a string and append it.
How to do it is a separate question that is out of scope for this question.