Skip to content

Instantly share code, notes, and snippets.

@Zheaoli
Created May 15, 2023 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zheaoli/d371dc073039edecf7faa77a8d6c0fd8 to your computer and use it in GitHub Desktop.
Save Zheaoli/d371dc073039edecf7faa77a8d6c0fd8 to your computer and use it in GitHub Desktop.
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json;
use bytes::Bytes;
#[derive(Clone, Debug, Deserialize, Serialize)]
struct DropboxDeleteArgs {
path: String,
}
#[tokio::main]
async fn main() {
let args=DropboxDeleteArgs{
path:"/test.txt".to_string()
};
Bytes::from(serde_json::to_string(&args).unwrap().to_string());
Bytes::from_static(serde_json::to_string(&args).unwrap().as_bytes());
}
@Zheaoli
Copy link
Author

Zheaoli commented May 15, 2023

我的问题首先来说,我的核心诉求是将 serde_json 序列化后的结果转化成 bytes::Bytes

  1. 我通过 Byte::from 解决了问题
  2. 我比较好奇的一个点是,我第二种方式 Bytes::from_static(serde_json::to_string(&args).unwrap().as_bytes()) 报错 creates a temporary value which is freed while still in use。我看了下函数签名是 bytes: &'static [u8],所以我理解是这里将一个所有权转换成 static 这样的东西将会存在计数问题,所以报错,不知道理解正确与否?以及我如果想强行将 as_bytes 这样动态的结果传进去,有什么优雅的方式吗?我查了一下,好像说没有 type safe 的方式,FYI https://users.rust-lang.org/t/convert-string-string-to-static-str/8197/2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment