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
CodePudding user response:
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
CodePudding user response:
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.