如何在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
相关产品推荐
相关产品推荐

