如何在golang中修剪和转义字符串指针?

huangapple go评论91阅读模式
英文:

How to trim and escape a string pointer in golang?

问题

用户名不是必需的,可以为nil,所以我将该属性指针化为字符串。

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

尝试修剪和转义时,出现错误:"无法将html.EscapeString(strings.TrimSpace(u.Username))(类型为string的值)用作*string赋值的值"。

英文:

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"

答案1

得分: 2

你需要通过*运算符访问指针的值。

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

更新

还要记得使用*运算符来赋值

*u.Username = html.EscapeString(strings.TrimSpace(*u.Username))
英文:

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

答案2

得分: 1

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

更好的示例在这里

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

better example here

huangapple
  • 本文由 发表于 2021年10月2日 14:37:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/69414599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定