gpt4 book ai didi

rust - FromSql::from_sql 的参数的生命周期是多少?

转载 作者:行者123 更新时间:2023-11-29 08:08:25 27 4
gpt4 key购买 nike

我将 Diesel 与 Postgres 一起使用,并希望将 text 字段查询为 *const str。柴油有实现FromSql for *const str .

文档描述:

The returned pointer is only valid for the lifetime to the argument of from_sql.

from_sql 参数的生命周期是多少?它与连接的生命周期相同吗?

最佳答案

from_sql将采取 Option<&'a DB::RawValue>并返回 Result<*const str> .

如果没有原始指针(并且具有显式生命周期),函数定义将类似于:

fn from_sql<'a>(bytes: Option<&'a DB::RawValue>) -> Result<&'a str>

输出到输入的生命周期在这里是显而易见的并且是静态检查的——但是对于原始指针,它不是:

fn from_sql<'a>(bytes: Option<&'a DB::RawValue>) -> Result<*const str>

警告只是指出你得到的指针只保证在 &'a DB::RawValue 的生命周期内有效。你传递给函数。如果没有原始指针,则警告是不必要的,因为编译器会保证 &str仅在引用时存在。

这是 from_sql的实现:

fn from_sql(bytes: Option<&DB::RawValue>) -> deserialize::Result<Self> {
use std::str;
let string = str::from_utf8(not_none!(bytes))?;
Ok(string as *const _)
}

输出的生命周期取决于 bytes 的原因参数是 str::from_utf8仅执行 UTF-8 验证并对 bytes 进行不安全转换到&str - 你基本上只是将输入作为不同的类型返回。 from_sql的结果只是指向您传递给它的相同数据的指针,因此该指针仅在输入数据有效时才有效。

关于rust - FromSql::from_sql 的参数的生命周期是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56268877/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com