【问题标题】:Go: (operator + not defined on slice)Go:(运算符+未在切片上定义)
【发布时间】:2014-07-25 14:53:48
【问题描述】:

我正在尝试编写一个程序,该程序接受用户输入标志,读取包含数据的输入文件(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)
}

【问题讨论】:

    标签: go append operator-keyword slice


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-05-21
      • 2017-10-04
      • 2013-04-14
      • 1970-01-01
      • 2022-01-25
      • 2021-06-11
      • 2020-10-10
      • 2021-03-13
      • 2014-07-17
      相关资源
      最近更新 更多