英文:
Output with curly braces
问题
我写了一个简单的函数,从一个CSV文件中查找并返回一个随机的大写字母名称。它运行得很好,但是即使输出是字符串类型,结果也会用花括号括起来。有人有什么办法可以去掉这些花括号吗?
func chosname(filePath string) string {
var persons []Person
rName := rand.Intn(1000) + 1000
isFirstRow := true
headerMap := make(map[string]int)
f, _ := os.Open(filePath)
r := csv.NewReader(f)
for {
// 读取行
record, err := r.Read()
// 在EOF处停止
if err == io.EOF {
break
}
checkError("发生其他错误", err)
if isFirstRow {
isFirstRow = false
for _, v := range record {
headerMap[v] = 0
}
continue
}
persons = append(persons, Person{
IMIEPIERWSZE: record[headerMap["IMIEPIERWSZE"]],
})
}
return fmt.Sprintf("%s", persons[rName])
}
输出:
{PAUL}
期望输出:
PAUL
英文:
I wrote simple function to find and return random name from a CSV file, where names are just a names written in capital letters. It works pretty well, but output is given in curly braces even if it is as a type of string. Anybody has an idead how to get rid of those curly braces?
func chosname(filePath string) string {
var persons []Person
rName := rand.Intn(1000) + 1000
isFirstRow := true
headerMap := make(map[string]int)
f, _ := os.Open(filePath)
r := csv.NewReader(f)
for {
// Read row
record, err := r.Read()
// Stop at EOF.
if err == io.EOF {
break
}
checkError("Some other error occurred", err)
if isFirstRow {
isFirstRow = false
for _, v := range record {
headerMap[v] = 0
}
continue
}
persons = append(persons, Person{
IMIEPIERWSZE: record[headerMap["IMIEPIERWSZE"]],
})
}
return fmt.Sprintf("%s", persons[rName])
}
Output:
{PAUL}
Wanted output: PAUL
答案1
得分: 2
由于默认的格式化,花括号将被打印出来,有一些解决方法可以解决这个问题,但最好的方法是为Person
类型实现String() string
方法,并根据需要添加自定义格式。
package main
import "fmt"
type Person struct {
IMIEPIERWSZE string
}
func (p Person) String() string {
return fmt.Sprintf("%s", p.IMIEPIERWSZE)
}
func main() {
fmt.Println(Person{"test"})
}
Playground: https://go.dev/play/p/gfnY_gn1kJ2
英文:
The curly braces will be printed out because of the default formatting and there are some several workarounds around that but the best of that would be to implement the String() string
method to the Person
type and add the custom formats as you need.
package main
import "fmt"
type Person struct {
IMIEPIERWSZE string
}
func (p Person) String() string {
return fmt.Sprintf("%s", p.IMIEPIERWSZE)
}
func main() {
fmt.Println(Person{"test"})
}
Playground: https://go.dev/play/p/gfnY_gn1kJ2
答案2
得分: 1
你在打印时也可以调用一个人的属性。
return fmt.Sprintf("%s", persons[rName].Name)
花括号是因为你在打印一个结构体。你可以选择上面@Hamza Anis提到的自定义格式化的方法,或者如果你只想打印人的名字,可以使用以下方法。
英文:
you can also call the property of a person while printing
return fmt.Sprintf("%s", persons[rName].Name)
the curly braces are printing because of you are printing a struct.
You can either choose the above answer @Hamza Anis mentioned with a custom formating or if you just want to print the name of the person you can just follow this method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论