Go :(操作符+未在切片上定义)

时间:2014-07-25 14:53:49

标签: go append operator-keyword slice

我试图编写一个带有用户输入标志的程序,读取包含数据的输入文件(testInput.txt),然后将用户的标志附加到输入数据并将其全部导出到输出文件(testOutput 。文本)。在尝试将两者附加在一起时,我在func employeeReadWrite()中收到错误。 "无效操作:内容+ cnvUserProfile(操作符+未在切片上定义)"。我是第一语言编程的新手,我还没有很好的处理片。我需要做些什么才能解决该错误?

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)
}

1 个答案:

答案 0 :(得分:4)

您无法在切片上使用+,但您可以使用append

 ioutil.WriteFile("testOutput.txt", append(contents, cnvrtUserProfile), 0x777)