Go:(运算符 + 未在切片上定义)

Yos*_*shi 2 append go slice operator-keyword

我正在尝试编写一个程序,该程序接受用户输入标志,读取包含数据的输入文件(testInput.txt),然后将用户的标志附加到输入数据并将其全部导出到输出文件(testOutput.txt)。当我尝试将两者附加在一起时,我在 func employeeReadWrite() 中遇到错误。“无效操作:内容+ cnvUserProfile(运算符+未在切片上定义)”。我是编程新手,go 是我的第一语言,而且我对切片还没有很好的掌握。我需要做什么来解决该错误?

package main

import (
"flag"
"fmt"
"io/ioutil"
"os"
)

var targetEmployee *string
var targetUsername *string
var targetLocation *string
var targetDepartment *string
var targetManager *string
var targetTitle *string
var userProfile string

func getFlagVariables() {
    targetEmployee = flag.String("employee", "", "What is there name? (-employee)")
    targetUsername = flag.String("username", "", "What is there username? (-username)")
    targetLocation = flag.String("location", "", "Where are the working from? (-location)")
    targetDepartment = flag.String("department", "", "What is there department? (-department)")
    targetManager = flag.String("manager", "", "Who is there manager? (-manager)")
    targetTitle = flag.String("title", "", "What is there job title? (-title)")

    flag.Parse()

    fmt.Println("-----------------------------------")
    userProfile = *targetEmployee + "\n" + *targetUsername + "\n" + *targetUsername + "@genericCompany.com" + "\n" + *targetLocation + "\n" + *targetDepartment + "\n" + *targetManager + "\n" + *targetTitle
    fmt.Println(userProfile)
    fmt.Println("-----------------------------------")

}

func employeeReadWriteFile() {
    contents, _ := ioutil.ReadFile("testInput.txt")
    cnvrtUserProfile := []byte(userProfile)
    ioutil.WriteFile("testOutput.txt", contents+cnvrtUserProfile, 0x777)
}
Run Code Online (Sandbox Code Playgroud)

One*_*One 5

您不能+在切片上使用,但可以使用append

 ioutil.WriteFile("testOutput.txt", append(contents, cnvrtUserProfile), 0x777)
Run Code Online (Sandbox Code Playgroud)