string concat error:期望一个文字

Cab*_*ero 2 rust

所以我有这个:

struct User {
    reference: String,
    email: String,
    firstname: String,
    lastname: String
}

fn main() {

    let user = User {
        reference: "ref".to_string(),
        email: "em@ail.com".to_string(),
        firstname: "John".to_string(),
        lastname: "Doe".to_string()
    };

    concat!(&user.firstname.as_string(), " ", &user.lastname.as_string());

}
Run Code Online (Sandbox Code Playgroud)

那是一个错误:

error: expected a literal
concat!(&user.firstname.as_string(), " ", &user.lastname.as_string());
        ^~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

但我认为.as_string()已经使它成为字面意义,不是吗?我也发现as_slice()as_str()引用了所有地方,这令人困惑.哪一个?

更新好的,我希望我不必在这里粘贴整个东西,但我想我还是必须这样做:

extern crate postgres;

use postgres::{Connection, SslMode};

struct User {
    reference: String,
    email: String,
    firstname: String,
    lastname: String
}

fn main() {

    let conn = Connection::connect("postgres://postgres:postgres@localhost/mydb", &SslMode::None).unwrap();

    let user = User {
        reference: "ref".to_string(),
        email: "em@ail.com".to_string(),
        firstname: "John".to_string(),
        lastname: "Doe".to_string()
    };
    let query = "INSERT INTO foo (user_id, name) VALUES ((SELECT id FROM user WHERE email = $1), $2)";
    conn.execute(query, &[&user.email, concat!(&user.firstname.as_slice(), " ", &user.lastname.as_slice())]).unwrap();

}
Run Code Online (Sandbox Code Playgroud)

Mat*_* M. 11

这里有误解.

concat!是一个宏,这是一个"代码生成"机制; 因此,在类型解析/所有权检查/等之前,它在编译的第一阶段进行了扩展...

文本是写入的一个值原样中的代码:true,1,"hello"; 表达式的结果不能是文字(根据定义).结果类型可能看起来相似(甚至相同),但这里的类型无关紧要.


那么,你真正想要的是什么?我想你只想连接字符串.对于String,你可以使用+:

let fullname = user.firstname + " " + user.lastname;
conn.execute(query, &[&user.email, &fullname]).unwrap();
Run Code Online (Sandbox Code Playgroud)

或者,如果您需要一些更复杂的格式,您可以使用format!宏(不需要文字),这里它将是:

let fullname = format!("{} {}", user.firstname, user.lastname);
Run Code Online (Sandbox Code Playgroud)