How write better this code

Hi everyone, i'm learning about rust, i created this small example like test.
This code is to decode a URI from String.

How to better this code?

trait Uri{ fn new( data : &mut String ) -> Self; }

struct Purl{
verb : String,
app : String,
res : String,
method : String,
qry : Vec,

impl Uri for Purl{

fn new( my_url : &mut String ) -> Purl{

 let mut struc = Purl{ 
                  		verb   : String::new(),
                        app    : String::new(),
                  		res    : String::new(),
                  		method : String::new(),
                  		qry    : vec![ String::new() ]

 let mut split : Vec<&str> = my_url.split(" ").collect();
 struc.verb = split.remove(0).to_string();
 let mut my_url : String  = split.remove(0).to_string();

 let mut split : Vec<&str> = my_url.split("/").collect(); = split.remove(1).to_string();
 struc.res = split.remove(1).to_string();
 my_url = split.remove(1).to_string();

 let mut split : Vec<&str> = my_url.split("?").collect();
 struc.method = split.remove(0).to_string();
 my_url = split.remove(0).to_string();

 let split : Vec<String> = my_url.split("&").map(|s| s.to_string() ).collect();
 struc.qry = split;


fn main() {

let mut my_url : String = "GET /clinica/pacientes/list?nome=almir&st=inativo&order=nome HTTP/1.1\r\n".to_string();

let struc : Purl = Purl::new( &mut my_url );

println!("{:?}", struc);


Here is a version of your code on the Rust Playground, with the standard Rust formatting rules applied - it's a good idea to post your code running on the playground when you need help so that people can try it themselves :slight_smile:


Some notes:

  • In your definition of Purl, qry is Vec, which isn't a type by itself; it needs to be Vec<String>.
  • You don't need to create an empty Purl before setting its parts, you can just create one from those parts at the end of new.
  • new doesn't need to take a &mut String; it works fine with just a &str.
  • Because data could be an invalid URL, new should return an Option<Purl> (or maybe a Result if you want to give info on how it's invalid.)
  • From this code alone, you don't really need the URI trait, unless there's some other way you want to parse request lines.
  • Instead of collecting intermediate values to Vecs and using remove, you can use Iterators directly.
  • AFAIK HTTP request lines don't have query parameters.

Here is a playground with updated code. It contains two implementations of new: the basic new which just directly pulls from split iterators, and new_itertools, which uses the itertools crate to simplify things into just a couple of lines.


Very cool, thanks for your response, i'll study the code. :wink:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.