作者:郑云雪 | 来源:互联网 | 2023-06-12 09:28
文章目录一、结构数组二、序列化三、反序列化一、结构数组constv0:i80;constv1:i81;constv2:i82;constv3:i83;structArr{v
一、结构数组
const v0: i8 = 0;
const v1: i8 = 1;
const v2: i8 = 2;
const v3: i8 = 3;struct Arr {v: i8,s: &'static str,
}const str: [Arr; 4] = [Arr {v: v0, s:"zero",},Arr {v: v1, s:"one",},Arr {v: v2, s:"two",},Arr {v: v3, s:"three",},
];fn main() {println!("{}", str[2].v);
}
初始化一些方法:
此方法安全,但是效率不高,会复制10份Foo { a: 10, b: 10}结构体。
#[derive(Copy, Clone, Debug)]
struct Foo {a: u32,b: u32,
}fn main() {let mut foo_array = [Foo { a: 10, b: 10 }; 10];
}
高效方法:
Cargo.toml
...
[dependencies]
arrayvec = "0.4.10"
main.rs
use arrayvec::ArrayVec;
use std::iter;#[derive(Clone)]
struct Foo {a: u32,b: u32,
}fn main() {let foo_array: [Foo; 10] &#61; iter::repeat(Foo { a: 10, b: 10 }).collect::<ArrayVec<_>>().into_inner().unwrap_or_else(|_| unreachable!());
}
或者
struct Foo {foo: isize,
}impl Foo {pub fn new(i: isize) -> Foo {Foo { foo: i }}
}fn main() {let foo_array: [Foo; N] &#61; [0..N].iter().map(|i| Foo::new(i));
}
二、序列化
Rust Crate 使用&#xff1a;serde
序列化和反序列化是非常通用的功能&#xff0c;在网络传输&#xff0c;数据存储上极其常见的。序列化和反序列化的通用解释是&#xff1a;
seriallization
序列化 &#xff1a; 将对象转化为便于传输的格式&#xff0c; 常见的序列化格式&#xff1a;二进制格式&#xff0c;字节数组&#xff0c;json字符串&#xff0c;xml字符串。
deseriallization
反序列化&#xff1a;将序列化的数据恢复为对象的过程。
格式编写者只需实现 Serde 的 trait
即可&#xff0c;而用户通过#[derive(Serialize&#xff0c;Deserialize)]
对其对象进行序列化&#xff0c;而无需考虑格式。
Cargo.toml
...
[dependencies]
serde &#61; { version &#61; "1.0", features &#61; ["derive"] }
serde_json &#61; "1.0.0"
...
use serde::{Serialize, Deserialize};#[derive(Serialize, Deserialize)]
struct Person {name: String,age: u8,phones: Vec<String>,weight: Option<u8>,
}fn main() {let data &#61; r#"{"name": "John Doe","age": 43,"phones": ["&#43;44 1234567","&#43;44 2345678"]}"#;let p: Person &#61; serde_json::from_str(data).unwrap();println!("Please call {} at the number {}", p.name, p.phones[0]);let serialized &#61; serde_json::to_string(&p).unwrap();println!("serialized &#61; {}", serialized);
}
关于更多&#xff1a;https://blog.logrocket.com/rust-serialization-whats-ready-for-production-today/
三、反序列化
use serde_json;
use std::result::Result;
use std::error::Error;
use serde::{Deserialize, Serialize};#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
enum Speech {Str(String),StrArray(Vec<String>),
}#[derive(Debug, Serialize, Deserialize)]
struct Foo {pub foo: String,#[serde(skip_serializing_if &#61; "Option::is_none")]speech: Option<Speech>,
} fn main() -> Result<(), Box<dyn Error>> {let json1 &#61; r#"{"foo": "bar","speech": "something"}"#; let json2 &#61; r#"{"foo": "bar","speech": ["something", "something else"]}"#; let json3 &#61; r#"{"foo": "bar"}"#; let foo1: Foo &#61; serde_json::from_str(json1)?;let back_to_str_foo1 &#61; serde_json::to_string(&foo1).unwrap();println!("foo1 {:#?}", foo1);println!("back_to_str_foo1 {}", back_to_str_foo1);let foo2: Foo &#61; serde_json::from_str(json2)?;let back_to_str_foo2 &#61; serde_json::to_string(&foo2).unwrap();println!("foo1 {:#?}", foo2);println!("back_to_str_foo2 {}", back_to_str_foo2);let foo3: Foo &#61; serde_json::from_str(json3)?;let back_to_str_foo3 &#61; serde_json::to_string(&foo3).unwrap();println!("foo1 {:#?}", foo3);println!("back_to_str_foo3 {}", back_to_str_foo3);Ok(())
}