将字符串文字与另一个字符串连接 [英] Concatenate string literal with another string

查看:87
本文介绍了将字符串文字与另一个字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否有某些原因无法将字符串文字与字符串变量连接在一起?以下代码:

Is there some reason why I cannot concatenate a string literal with a string variable? The following code:

fn main() {
    let x = ~"abcd";
    io::println("Message: " + x);
}

出现此错误:

test2.rs:3:16: 3:31 error: binary operation + cannot be applied to type `&'static str`
test2.rs:3     io::println("Message: " + x);
                           ^~~~~~~~~~~~~~~
error: aborting due to previous error

我想这是一个非常基本且非常常见的模式,在这种情况下使用 fmt!只会带来不必要的混乱。

I guess this is a pretty basic and very common pattern, and usage of fmt! in such cases only brings unnecessary clutter.

推荐答案

默认情况下,字符串字面量具有静态生存期,并且无法连接唯一和静态向量。使用唯一的文字字符串有助于:

By default string literals have static lifetime, and it is not possible to concatenate unique and static vectors. Using unique literal string helped:

fn main() {
    let x = ~"abcd";
    io::println(~"Message: " + x);
}

这篇关于将字符串文字与另一个字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆