#How to extend async_std WriteExt with extension trait?

13 messages · Page 1 of 1 (latest)

topaz obsidian
#

I want to send json with TcpStream and I'm using something like this everytime:

let json_str = serde_json::to_string(&json)?;
stream.write(json_str.as_bytes()).await?;

I want to write an extension to WriteExt like this:

stream.write_json(&json);

And inside of it, it will do exactly written above. Can you give me any idea how can I do it? I tried to write a helper trait but couldn't manage. Thanks a lot!

low kettle
topaz obsidian
low kettle
#

it would be serde_json::to_writer(&mut stream, &json)?;

topaz obsidian
#

Yeah that is a way, but I'm asking how can I write my own extension trait because I want to add some extra stuff too. For example print something everytime when I send a json. So when I called something like stream.write_json(&json).await?; it should run my custom extension codes and sends the json. Is it possible?

#

I found something like this bu in async WriteExt it becomes little bit a maze 😄

low kettle
#

I would recommend starting with writing your own functions

#

extension traits are another layer of complexity and they only give you .foo() syntax

#

they do not give you any more power

#

so just write a function that takes the stream and the json and does the two things you want

#

oh, I did misunderstand your original question

#

my answer was about "how can I avoid constructing a temporary string"