在Go语言中,允许在一个字符串中使用多个参数。

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

Allowing more than one argument in a string [Go]

问题

我正在使用Gomail从表单中获取数据并将其通过电子邮件发送给自己。如果我想要获取用户的全名,我会使用以下代码:

  1. m.SetBody("text/html", fmt.Sprintf("<b>全名</b>: %s", msg.completeName))

在电子邮件中会显示如下内容:

全名: John Michael Smith

现在,如果我想要在代码中添加一个消息字段:

  1. 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:

  1. m.SetBody(&quot;text/html&quot;, fmt.Sprintf(&quot;&lt;b&gt;Full Name&lt;/b&gt;: %s&quot;, 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

  1. m.SetBody(&quot;text/html&quot;, fmt.Sprintf(&quot;&lt;b&gt;Full Name&lt;/b&gt;: %s&quot;, msg.completeName, &quot;&lt;br&gt; &lt;b&gt;Message&lt;/b&gt; %s&quot;, 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需要一个字符串格式作为第一个参数,然后是你需要插入最终字符串中的所有变量。

因此,你的代码应该是这样的:

  1. m.SetBody("text/html", fmt.Sprintf("<b>Full Name</b>: %s <br><b>Message</b> %s", msg.completeName, msg.Content))

如果想了解更多信息,建议你阅读Sprintf文档

注意:在评论中,我说“为什么不连接字符串?”因为你也可以这样做:

  1. 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:

  1. m.SetBody(&quot;text/html&quot;, fmt.Sprintf(&quot;&lt;b&gt;Full Name&lt;/b&gt;: %s &lt;br&gt;&lt;b&gt;Message&lt;/b&gt; %s&quot;, 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:

  1. m.SetBody(&quot;text/html&quot;, &quot;&lt;b&gt;Full Name&lt;/b&gt;: &quot;+ msg.completeName +&quot; &lt;br&gt;&lt;b&gt;Message&lt;/b&gt; &quot; + msg.Content))

huangapple
  • 本文由 发表于 2016年4月11日 01:15:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/36532909.html
匿名

发表评论

匿名网友

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

确定