字符串连接错误:需要文字 [英] string concat error: expected a literal
问题描述
所以我有这个:
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());
}
返回错误:
error: expected a literal
concat!(&user.firstname.as_string(), " ", &user.lastname.as_string());
^~~~~~~~~~~~~~~~~~~~~~~~~~
但我认为 .as_string()
已经使它成为一个文字,不是吗?我还发现到处都是 as_slice()
和 as_str()
引用,这很令人困惑.是哪个?
But I thought that .as_string()
already makes it a literal, does it not? I am also finding as_slice()
and as_str()
references all over the place and it's confusing. Which one is it?
更新好吧,我希望我不必在这里粘贴整个内容,但我想无论如何我都必须这样做:
UPDATE OK, I was hoping I don't have to paste the whole thing here, but I guess I just have to do that anyway:
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();
}
推荐答案
这里有误会.
concat!
是一个宏,即代码生成"机制;因此它在编译的第一阶段被扩展,在类型解析/所有权检查/等之前......
concat!
is a macro, that is a "code-generation" mechanism; as a result it is expanded at the first stages of the compilation, before type resolution/ownership checks/etc...
文字是代码中按原样写入的值:true
, 1
, "hello"
;表达式的结果不能是文字(根据定义).结果类型可能看起来相似(甚至完全相同),但类型在这里无关.
A literal is a value written as-is in the code: true
, 1
, "hello"
; the result of an expression cannot be a literal (by definition). The resulting types may look similar (or even be identical) but types are irrelevant here.
那么,你真正想要的是什么?我猜你只是想连接字符串.对于 String
,你可以使用 +
:
So, what do you really want? I guess you just want to concatenate strings. For String
, you can just use +
:
let fullname = user.firstname + " " + user.lastname;
conn.execute(query, &[&user.email, &fullname]).unwrap();
或者,如果您需要一些更复杂的格式,您可以使用 format!
宏(不需要文字),这里是:
Alternatively, if you need some more complex formatting, you can use the format!
macro (which does not require literals), here it would be:
let fullname = format!("{} {}", user.firstname, user.lastname);
这篇关于字符串连接错误:需要文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!