rust string str?你想在Rust学习吗?Go考虑简单字符串插值特性
大家好,我是煎鱼。在日常开发 Go 工程中,我们经常会用 fmt.Printf 或 fmt.Sprintf 去写类似的拼装字符串的业务。如下代码:fmt.Printf("Hello Gopher %s
顺晟科技
2023-02-26 09:32:57
70
你好,我是烤鱼。
在日常开发Go项目中,fmt。Printf或fmt。经常使用Sprintf编写类似的装配字符串。
以下代码:
fmt . printf(& amp;# 039;hello gopher% s、you are % d years old and you & amp# 039;re favorite food is % s & amp# 039;name、age、favood小型计算机显示不足以在一行中显示代码。
虽然有很多把字符串变成变量的特性,但是后面那些又臭又长的变量仍然不能轻易甩掉,所以大多数同学都选择了格式化代码。
以下代码:
s:=& amp;# 039;hello gopher% s、you are % d years old and you & amp# 039;re favorite food is % s & amp# 039;
Fmt。Printf(
s,
Name,
艾吉,
FavoriteFood,
)你能认为这是个例子吗?事实上,很多人都见过。
这一点在Go issues进行了3-4年的社区讨论,@Ian Lance Taylor发起了新提案《proposal: spec: add simple string interpolation similar to Swift》。希望能得到更多的讨论,增加新的功能来解决这个问题。
此新功能类似于简单版本的Swift字符串插值。我直接看例子。
fmt . print ln(& amp;# 039;\(person . name())is \(person . age())years old & amp;# 039;)
fmt . print ln(& amp;# 039;thetimeis \ (time.now())。与round (0))相对应的输出结果:
Ken Thompson is 79 years old
the time is 2023-01-04 16:22:01.204034106-0800 PST计划书程序中新增的字符串插值如下:
新转义语法:\(xxxx),开始\(,结束),成对出现。格式中必须有有效的\(,后面是表达式和尾部),才能生效。在上例中,以下是字符串插值:
\(person)。Name())
\(person)。Age()
\(time)。Now()。Round(0))会有学生疑惑person看起来像结构的东西怎么有价值。
Go有神奇的规则方法,如结构,如果有String() string方法,则调用该方法以获取字符串值。
如果没有String方法,则需要以下类型:字符串、整数、浮点、多个、常量或布尔。可以导入值并设置其格式。否则就会报告错误。
let multiplier=3
Letmessage=& amp# 039;\(multiplier)times 2 . 5 is \(double(multiplier)* 2 . 5)& amp;# 039;
//message is & amp;# 039;3 times 2.5 is 7.5 & amp# 039;
var age=21
print ln(& amp;# 039;myage is:$ age & amp;# 039;)
字串名称=& amp# 039;mark & amp# 039;
Var date=DateTime。Now
console . writeline($ & amp;# 039;hello,{name}!Todayis {date.dayofweek},it & amp# 039;s {date: hh: mm} now。& amp# 039;);
let person=get _ person();
Println!(& amp# 039;hello,{person}!& amp# 039;);//captures the local & amp;# 039;person & amp# 039;
Println!(& amp# 039;hello,{}!& amp# 039;get _ person();//implicit position
Println!(& amp# 039;hello,{0}!& amp# 039;get _ person();//explicit索引
Println!(& amp# 039;hello,{person}!& amp# 039;person=get _ person();//named
Let(宽度,precision)=get _ format();
For (name,score) in get_scores() {
Println!(& amp# 039;{name}: {score: width $。precision $ } & amp# 039;);
fmt是
目前的主要问题之一。像Sprintf这样的方法也可以产生与字符串插值相同的效果。为什么要添加这个功能特性(或者语法党)?
主流观点是传统的字符串格式化方法,参数数多了容易出错(如顺序错误),是比较松散的大代码块。
通过添加字符串插值的特性/语法糖,可以更好地读取和修改变量,而不会过度依赖于创建变量的顺序。
具体例子如下:现有版本代码。
Errorf (pos、& amp# 039;arguments to copy % s and % s have different element types % s and % s & amp;# 039;x、y、dst.elem)
错误(pos、& amp# 039;arguments to copy \(x)and \(y)have different element types \(dst . elem)and \
如果您是长期维护多个项目的开发人员,您可以继续添加、更改现有格式字符串,以及插入新添加的字符串。
未来几年你会选择哪一个?还是有新想法?
文章更新,可以微信搜索[头脑炸鱼]阅读,文章包括GitHub github.com/eddycjy/blog,学习Go语言Go学习指导和路径,欢迎入门提醒。
Go语言入门系列:Go项目实战Go语言编程旅行:深入使用Go作为项目Go语言设计哲学:Go的理由和设计思维,Go语言高级旅行:Go源代码
!Go加强了Go1的向后兼容性,打兄弟们,Go1.20 arena来了!高十年,终于想起统一日志库了!