Home > front end >  How to trim and escape a string pointer in golang?
How to trim and escape a string pointer in golang?

Time:10-02

Username is not required and it can be nil, so I made this property pointer to string.

type User struct {
    Username *string `json:"username"`
    Email    string `json:"email"`
    Password string `json:"password"`
}

func (u *User) PrepareUser() {
    if u.Username != nil {
        u.Username = html.EscapeString(strings.TrimSpace(u.Username))
    }
    u.Email = html.EscapeString(strings.TrimSpace(u.Email))
    u.Password = strings.TrimSpace(u.Password)
}

When trying to trim and escape I see "cannot use html.EscapeString(strings.TrimSpace(u.Username)) (value of type string) as *string value in assignment"

CodePudding user response:

You need to access the value of pointer via * operator.

html.EscapeString(strings.TrimSpace(*u.Username))

Update

Also don't forget to use * operator for assigning value

*u.Username = html.EscapeString(strings.TrimSpace(*u.Username))

CodePudding user response:

func trimEscapeStrPtr(s *string) *string {
    t := html.EscapeString(strings.TrimSpace(*s))
    return &t
}

better example here

  •  Tags:  
  • go
  • Related