You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust中手动构造rusoto_dynamodb的AttributeValue?

在Rust中创建rusoto_dynamodb的AttributeValue类型

你遇到的问题是AttributeValue没有直接实现从&str或String的From trait,所以无法直接用from方法转换。你猜测要用到s字段是正确的,DynamoDB的字符串类型对应AttributeValue的s字段,下面是具体实现方式:

方法一:直接构造结构体

手动指定s字段的值,其他字段用默认的None填充:

use rusoto_dynamodb::AttributeValue;
use std::collections::HashMap;

fn main() {
    let mut my_map = HashMap::new();
    my_map.insert(
        String::from("key1"),
        AttributeValue {
            s: Some(String::from("value1")),
            ..AttributeValue::default()
        }
    );
}

方法二:使用辅助构造函数(推荐)

rusoto_dynamodb提供了大写字母命名的辅助函数,快速创建对应类型的AttributeValue,字符串类型用AttributeValue::S:

use rusoto_dynamodb::AttributeValue;
use std::collections::HashMap;

fn main() {
    let mut my_map = HashMap::new();
    my_map.insert(String::from("key1"), AttributeValue::S(String::from("value1")));
}

错误原因说明

你之前的代码报错,是因为AttributeValue没有为&str实现From trait,Rust编译器找不到从&str到AttributeValue的自动转换路径,所以提示“expected struct AttributeValue, found &str”——意思是此处需要AttributeValue类型,但你传入了&str类型,没有匹配的转换规则。

内容的提问来源于stack exchange,提问作者Richard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 07:32:38