英文:
Allowing more than one argument in a string [Go]
问题
我正在使用Gomail从表单中获取数据并将其通过电子邮件发送给自己。如果我想要获取用户的全名,我会使用以下代码:
m.SetBody("text/html", fmt.Sprintf("<b>全名</b>: %s", msg.completeName))
在电子邮件中会显示如下内容:
全名: John Michael Smith
现在,如果我想要在代码中添加一个消息字段:
m.SetBody("text/html", fmt.Sprintf("<b>全名</b>: %s<br><b>消息</b> %s", msg.completeName, msg.Content))
它会输出如下内容:
全名: John Michael Smith%!(EXTRA string=
消息: %s, string=Hi there!.)
我希望它看起来像这样:
全名: John Michael Smith
消息: Hi there!
英文:
I'm using Gomail to grab data from a form and email it to myself. If I wanted to get the users full name, this is what I would use:
m.SetBody("text/html", fmt.Sprintf("<b>Full Name</b>: %s", msg.completeName))
It something like this in the email:
Full Name: John Michael Smith
Now if I wanted to add a message field to the code
m.SetBody("text/html", fmt.Sprintf("<b>Full Name</b>: %s", msg.completeName, "<br> <b>Message</b> %s", msg.Content))
It outputs this:
Full Name: John Michael Smith%!(EXTRA string=
Message: %s, string=Hi there!.)
I want it to look like this:
Full Name: John Michael Smith
Message: Hi there!
答案1
得分: 6
问题在于你错误地使用了Sprintf。
Sprintf
需要一个字符串格式作为第一个参数,然后是你需要插入最终字符串中的所有变量。
因此,你的代码应该是这样的:
m.SetBody("text/html", fmt.Sprintf("<b>Full Name</b>: %s <br><b>Message</b> %s", msg.completeName, msg.Content))
如果想了解更多信息,建议你阅读Sprintf文档。
注意:在评论中,我说“为什么不连接字符串?”因为你也可以这样做:
m.SetBody("text/html", "<b>Full Name</b>: "+ msg.completeName +" <br><b>Message</b> " + msg.Content))
英文:
The issue is that you're using Sprintf the wrong way.
The Sprintf
needs a string format as first argument and then all the variables you need to be inserted in the final string.
Thus your code should be:
m.SetBody("text/html", fmt.Sprintf("<b>Full Name</b>: %s <br><b>Message</b> %s", msg.completeName, msg.Content))
For more informations I suggest you to read the Sprintf documentation
NOTE: In the comment I said "why don't you concatenate the string?" since you can also do:
m.SetBody("text/html", "<b>Full Name</b>: "+ msg.completeName +" <br><b>Message</b> " + msg.Content))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论