How to pass a modified string parameter?


kaan_a

I'm in chapter 12 of the Rust programming language, which implements a case-insensitive line search. It doesn't make sense to me to implement the same logic twice, so I figured out if I just call the case-sensitive search function with a case-sensitive argument, that might work. It doesn't.

Here is my invalid code:

fn main() {
    let a = search("Waldo", "where in\nthe world\nis Waldo?");
    let b = search("waldo", "where in\nthe world\nis Waldo?");
    let c = search_case_insensitive("waldo", "where in\nthe world\nis Waldo?");

    println!("{:?}", a);
    println!("{:?}", b);
    println!("{:?}", c);
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }

    results
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let query = query.to_lowercase();
    let contents2: &str = &contents.to_lowercase();

    search(&query, contents2)
}

The errors in most of the versions I've come up with are inevitably very similar:

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:25:28
   |
25 |     let contents2: &str = &contents.to_lowercase();
   |                            ^^^^^^^^^^^^^^^^^^^^^^^ temporary value does not live long enough
...
28 | }
   | - temporary value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 23:1...
  --> src/main.rs:23:1
   |
23 | pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Simon Whitehead

Edit 2:

Now that you've updated your question with MCVE, and have stated that you're not worried about deviating from the book's example... Here's another version that relies on the extra assignment by using String:

fn main() {
    let a = search("Waldo", "where in\nthe world\nis Waldo?");
    let b = search("waldo", "where in\nthe world\nis Waldo?");
    let c = search_case_insensitive("waldo", "where in\nthe world\nis Waldo?");

    println!("{:?}", a);
    println!("{:?}", b);
    println!("{:?}", c);
}

pub fn search<S>(query: S, contents: S) -> Vec<String> where S: Into<String> {
    let query = query.into();
    let mut results = Vec::new();

    for line in contents.into().lines() {
        if line.contains(&query) {
            results.push(line.into());
        }
    }

    results

}

pub fn search_case_insensitive<S>(query: S, contents: S) -> Vec<String> where S: Into<String> {
    let query = query.into().to_lowercase();
    let contents = contents.into().to_lowercase();

    search(query, contents)
}

it runs in the playground

edit:

I realize I never really gave you other options. Here's what I might do:

pub enum SearchOptions {
    CaseSensitive,
    CaseInsensitive
}

pub fn search<'a>(query: &str, contents: &'a str, options: SearchOptions) -> Vec<&'a str> {
    let mut results = Vec::new();

    for line in contents.lines() {
        let check = match options {
            SearchOptions::CaseSensitive => line.contains(query),   
            SearchOptions::CaseInsensitive => line.to_lowercase().contains(&query.to_lowercase()),   
        };
    
        if check {
            results.push(line);
        }
    }

    results
}

This is about "deduplication".

Original answer:

The actual problem is that you are trying to pass it contentswhen it is tied to the lifecycle 'a. However, what you really want to be "case insensitive" is query.

This is not bound to lifetime in 'aexactly the same way , so... works:

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    let query = query.to_lowercase();
    search(&query, contents)
}

this is in the playground

However, you still need to repeat the logic...because you need to match lowercase queries to lowercase rows...this is demonstrated in the book's example:

if line.to_lowercase().contains(&query) {
//      ^^^^^^^^^^^^^^ each LINE is converted to lowercase here in the insensitive search
    results.push(line);
}

"How do I stop repeating logic?" - well, they weren't quite the same in the first place. I don't think your attempt is quite the same as the original one (nice to be corrected though).

Related


How to pass a modified string parameter?

kaan_a I'm in chapter 12 of the Rust programming language, which implements a case-insensitive line search. It doesn't make sense to me to implement the same logic twice, so I figured out if I just call the case-sensitive search function with a case-sensitive

How to pass a modified string parameter?

kaan_a I'm in chapter 12 of the Rust programming language, which implements a case-insensitive line search. It doesn't make sense to me to implement the same logic twice, so I figured out if I just call the case-sensitive search function with a case-sensitive

How to pass a modified string parameter?

kaan_a I'm in chapter 12 of the Rust programming language, which implements a case-insensitive line search. It doesn't make sense to me to implement the same logic twice, so I figured out if I just call the case-sensitive search function with a case-sensitive

How to pass a modified string parameter?

kaan_a I'm in chapter 12 of the Rust programming language, which implements a case-insensitive line search. It doesn't make sense to me to implement the same logic twice, so I figured out if I just call the case-sensitive search function with a case-sensitive

How to pass a modified string parameter?

kaan_a I'm in chapter 12 of the Rust programming language, which implements a case-insensitive line search. It doesn't make sense to me to implement the same logic twice, so I figured out if I just call the case-sensitive search function with a case-sensitive

How to pass a modified string parameter?

kaan_a I'm in chapter 12 of the Rust programming language, which implements a case-insensitive line search. It doesn't make sense to me to implement the same logic twice, so I figured out if I just call the case-sensitive search function with a case-sensitive

How to pass string as parameter name?

username I have the following function: def create_act(user, verb, fk_name=None, fk_value=None): fk = getattr(Action, fk_name) action = Action(user=user, verb=verb, fk=fk_value) action.save() Action is a class. The class has multiple properties an

How to pass string in url parameter?

not any From API i get something like this: processId=22, now i want to pass it in url parameter but the problem is i need to pass key and value. How can i paste the whole string as parameter. Any suggestions? So what I want to achieve is: <a *ngIf="menu.refPa

How to pass string as parameter name?

username I have the following function: def create_act(user, verb, fk_name=None, fk_value=None): fk = getattr(Action, fk_name) action = Action(user=user, verb=verb, fk=fk_value) action.save() Action is a class. The class has multiple properties an

How to pass multiline String parameter?

username Suppose I have this method: def read_line_by_line(some_text) some_text.each |line| do (something) end end How can I do this? I have got: my first line of the input text I tried to pass it as a parameter but got a weird output. It doesn't read line

How to pass string parameter in innerhtml

Khurshid Ansari I am creating dynamic html basic server response. example: var responseServer = { name: "al the' too" } var htmlView = `<div onclick="info(responseServer.name)"> </div>`; //Error: al identifier is not defined. var htmlView = `<div onclick="

How to pass string as parameter name?

username I have the following function: def create_act(user, verb, fk_name=None, fk_value=None): fk = getattr(Action, fk_name) action = Action(user=user, verb=verb, fk=fk_value) action.save() Action is a class. The class has multiple properties an

How to pass multiline String parameter?

username Suppose I have this method: def read_line_by_line(some_text) some_text.each |line| do (something) end end How can I do this? I have got: my first line of the input text I tried to pass it as a parameter but got a weird output. It doesn't read line

How to pass string parameter in java as parameter at runtime

username I am new to Java and I need help because how to get the value at runtime when executing a Java file. I have a Java program where the values of host, user, password and command are hardcoded, how can I parameterize them. E.g, public static void mai

How to pass string parameter in java as parameter at runtime

username I am new to Java and I need help because how to get the value at runtime when executing a Java file. I have a Java program where the values of host, user, password and command are hardcoded, how can I parameterize them. E.g, public static void mai

How to pass string parameter in java as parameter at runtime

username I am new to Java and I need help because how to get the value at runtime when executing a Java file. I have a Java program where the values of host, user, password and command are hardcoded, how can I parameterize them. E.g, public static void mai

How to pass string parameter in java as parameter at runtime

username I am new to Java and I need help because how to get the value at runtime when executing a Java file. I have a Java program where the values of host, user, password and command are hardcoded, how can I parameterize them. E.g, public static void mai

How to pass Persian string as parameter in URL?

shafizadi I have a URL like this: www.example.com/ClassName/MethodName/Arg1/Arg2 Here is my .htaccessfile too: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA] ErrorDocument

How to pass string parameter to url in view?

Smith I have a url that takes any string as a parameter. When I redirect to that URL, I want to pass parameters inside the view. How do you do this in Django? I have urls defined like this: url(r'^user_view/(?P<service_name>.+)$', views.user_view, name='user_v

How to pass a string as a parameter containing multiple strings

autumn My code is as follows: var args = "arg1,arg2" //come from external and also many e.g. arg3,arg4 ... df.select(args.split(","):_*) and then get the error: :31: error: ': *' annotations are not allowed here (such annotations are only allowed in arguments

How to pass string parameter to custom repository method?

MocaccinoFan I have a problem with AJAX + Rest + Spring boot + MySQL. The request was successful, but the response was empty, regardless of the format used in the request. Actually, the request payload shows ["customer":"MyCustomer"], so I think the problem is

How to pass string parameter to AsyncTask in Android

Martin It's really easy, but I'm stuck for an hour or so now. I am going through String[]a AsyncTaskclass like this class test extends AsyncTask<String, Void, Void>{ @Override protected Void doInBackground(String... params) { // Again, use either p

How to pass string parameter to javascript function

arrow Here is my front end: ImageButton Details = (ImageButton)e.Row.FindControl("iBtnDetails");//take lable id String strApplication1 = Details.CommandArgument.ToString(); e.Row.Attributes["onmouseover"] = "this.style.cursor='

How to pass [] string as...interface{} parameter

I understand: I know when the parameter is... strings But this case is a little different: func main() { args := []string{"hello", "world"} fmt.Println(args...) } https://play.golang.org/p/7ELdQQvdPvR The above code throws the errorcannot use args (ty

How to pass string as parameter to thread in C

dog I'm new to C and programming and I'm trying to pass a string to a thread for later manipulation. I tried creating the string using the array char string[] = "word"and passing it to the thread - pointers with char *word = "word"no luck now . How to pass str

How to pass constexpr string array as parameter?

who I am I have a file that contains an array of strings representing some icons. static constexpr char icons1[2][40] = { "icon1_A", "icon1_B" }; static constexpr char icons2[3][30] = { "icon22_A", "icon2_B", "icons2_C" }; Then I have a class that I want

How to pass string variable as parameter to awk

Prakash v Holka I have the following commands: usb_soundcard_sink=$(pactl list short sinks | grep "alsa_output" | awk '{ print $2 }' | tail -n1) The output of this command is: alsa_output.pci-0000_00_1b.0.analog-stereo Here is another command to find the ind