All Questions
617 questions
-1
votes
1
answer
102
views
Why is this string list/vector not getting updated?
I have a simple program where there is a vector of strings. Pressing one button adds items to this vector. Pressing another button should print out current contents of this vector. My code is a ...
4
votes
1
answer
65
views
What sort order does Rust's built-in cmp for &str use?
As I understood from this question, there are many ways to interpret the order of two strings.
Rust provides a default implementation for Ord for str, but I can't find the answer to these questions:
...
2
votes
1
answer
91
views
What is the idiomatic way to build hierarchical const &str values?
I would like to define a const &str that uses the value of another const &str. What is the standard way to do this in Rust?
const FOO: &str = "foo";
const FOOBAR: &str = FOO +...
0
votes
1
answer
110
views
The from_utf8 Rust function cannot read some ASCII strings (invalid utf-8 sequence of 1 bytes)
I am trying to convert a vector of ASCII bytes into a rust string. I found the std::str::from_utf8() function, that should be able to handle all ASCII strings. For some reason it cannot read the ...
1
vote
1
answer
66
views
What is the best way to concatenate two rust ffi::CString?
I was unable to find a method for ffi::CString concatenation, so I did the following:
// c_str1: CString
// c_str2: CString
...
let str1 = c_str1.to_str().unwrap();
let str2 = c_str2.to_str().unwrap();...
0
votes
0
answers
40
views
How can I convert a string to "unix mode bits" u32 in rust [duplicate]
I am trying to convert a string value (taken from environment variables) to unix mode bits used in the std::fs::Permissions::from_mode() method. I haven't found much on the subject and am hoping this ...
4
votes
1
answer
94
views
What's the best borrowing accessor pattern for Optional<String>?
This rust-analyzer style guide recommends accessors like this:
struct Person {
// Invariant: never empty
first_name: String,
middle_name: Option<String>
}
impl Person {
fn ...
0
votes
2
answers
95
views
How can I avoid Rc<String> extra pointer indirection?
I'm writing a bit of code that uses Rc<String>. I'm pretty sure that using this would create an extra pointer indirection, with one pointer to the Rc, which has a pointer to String, which is a ...
0
votes
0
answers
52
views
How to test a function that does write!, by sending a Vec<u8> in with Box<dyn Write>
I'd like to have a function that either writes to stdout or to a Vec. This is for an interactive CLI I would like to write tests for.
This works:
// To stdout
write!(std::io::stdout(), "{}", ...
0
votes
1
answer
24
views
How to dynamically use plotter SegmentValue?
I have a struct Band:
pub struct Band{
pub name: String,
pub start_dt: NaiveDateTime,
pub end_dt: NaiveDateTime,
pub stage: String,
pub selected: bool,
}
I'm using the plotters ...
-1
votes
1
answer
93
views
Iterate through a ReadDir and append file names to an array in Rust
I am trying to use the fs::read_dir() and iterate through the results and append all file names to an array. Something like this, except this isn't working:
let mut result: Vec<&str> = Vec::...
1
vote
1
answer
50
views
Replacing any sequences of spaces, tabs, newlines etc with single spaces using nom
I am learning parsing with nom right now and There's a few problems that pop up that I cannot solve myself. One I'd like to ask here.
First: I am not sure, if I actually need to use nom for this, but ...
0
votes
4
answers
104
views
Idiomatic way to have nth character different
I'm trying to do something relatively simple: get a string with the nth character different. So, for example,
let x = "XXXX";
let n = 2;
// code
"XXOX"
I'm well aware that this ...
0
votes
1
answer
131
views
How to extract first/last alphanumeric character from String
I have a seemingly simple problem of extracting a first and a last alphanumeric character from a String in Rust. Please consider my minimalistic example below:
fn main() {
let s: String = "...
2
votes
2
answers
104
views
Does an empty string allocate when converted to a Box<str>?
I'm using a message passing architecture for my app. One type that's commonly passed around is io::Result<Box<str>>. Sometimes, I want to pass around an empty string. Does any allocation ...
-1
votes
1
answer
59
views
Rust newbie compile error (for (key: String, value: String) in | ^ expected one of `)`, `,`, `@`, or `|`) [duplicate]
I just read through the first three chapters of the Rust Programming Language, and am currently trying to apply my limited knowledge building a CLI weather app with the help of a YouTube tutorial.
I ...
2
votes
2
answers
332
views
How to check that a string is among a fixed set of values in rust?
I want to check if the value of a string is among a fixed set of values. I tried the following (s is a String):
["foo", "bar", "baz"].contains(&*s)
The compiler says ...
1
vote
0
answers
53
views
How to perform lookaheads with string iterators?
I want to try to get familiar with Rust, so I'm attempting Crafting Interpreters. In the Longer Lexemes section it has a peek function that gets the character one ahead of the current index.
I'm not ...
-2
votes
1
answer
100
views
What is the difference between a hex decoded string and a string.as_bytes()?
I am hashing a string.
let src = String::from("abcd12342020");
let h1 = sha2::Sha256::digest(&src.as_bytes());
let h2 = sha2::Sha256::digest(hex::decode(&src).expect("this is ...
0
votes
0
answers
29
views
What is the correct way to compare static immutable strings and mutable strings in Rust? [duplicate]
I am new to Rust & I am having trouble to compare mutable strings and immutable strings.
Please find below a code block which should exit if "exit" is entered.
But I am having problem ...
0
votes
0
answers
94
views
Rust string manipulation, flow control improvements
I am new to the language and currently learning from the rust programming book.
I am wondering if there are any better way to improve my code. Especially the 2 pop (not sure if its the best practice)
...
0
votes
1
answer
63
views
Why is the last character from user input not correct? [duplicate]
I am trying to get the last value of a string from user input. I tried implementing it but it does not give the expected output:
println!("Please input temp (ex: 60F): ");
let mut temp = ...
1
vote
0
answers
195
views
how to intern a dynamically-created String in Rust?
I'm trying a generate some template based Strings:
let username;//unknown at compile time
let template = "(|$|)"; //might be anything
let st = template.replace('$', username);
//do ...
1
vote
2
answers
167
views
why do environment variables have String type instead of string slice in Rust?
for immutable, constant strings we use &str. for example,
let url: &'static str = "yourUrl";
The url is a constant value and doesn't need to be modified. It's a reference to a ...
0
votes
1
answer
55
views
Convert Vector<String> to CStrings
I want to pick an argument given to my program, convert it to CString and pass it as zero-terminated const char* to a C function.
let args: Vec<String> = env::args().collect();
let arg1 = args[1]...
0
votes
2
answers
429
views
Combining multiple iterators over same range in Rust
I am trying to understand how (and why) Rust iterators over the same span can not be combined (easily?).
Here's the code fragment causing the issues:
let fold_size = 1;
let field = "12345678\...
1
vote
1
answer
114
views
How to create a string literal
You just want to create a string literal like "Hello, world!" and print it out. How should you do this?
let str = "Hello, world!";
// or
let str = String::from("Hello, world!&...
-1
votes
2
answers
450
views
How do I convert a CString into a String with Rust?
I have a CString that I'm reading from disk. I created it with CStr::from_bytes_until_nul. My end goal though is to have a String, not a CString. I'm trying to store my CString into a struct that ...
1
vote
1
answer
95
views
Get original slices of &str in relation to parent String
Let's say I have a String, from which I take a slice (&str). Is it possible to find out the start and end positions of that slice, just by having the slice itself?
Example:
let original_string = ...
0
votes
1
answer
72
views
Unable to bound lifetime in for each loop using str.lines() function
I'm new to rust and i'm building an implementation of the grep command to learn this language.
I'm trying to create a function to match the search query in a case insensitive way, but i'm having ...
1
vote
1
answer
295
views
Why can a `str` type be of any size (unknown size) while a `String` type size is supposedly known?
I was learning Rust with a book and the following excerpt threw me a bit off:
Also note that &str has the & in front of it because you need a reference to use a str. That's because of the ...
2
votes
2
answers
847
views
Return string how to fix cannot return value referencing temporary value
I want to filter the msg in debug_args function before returning:
pub trait MyLog {
fn debug_args(&self) -> &dyn std::fmt::Debug;
}
pub struct TracingMyLog<'a> {
record: &...
2
votes
1
answer
174
views
Rust convert iterator over String to &[&str]
How do I convert an iterator that returns Strings to something that I can pass into a function that takes &[&str]? I'm trying to map the iterator to an iterator over &strs, but I get an ...
4
votes
2
answers
311
views
How do you select a struct based on a string in Rust?
Problem Statement
I have a set of structs, A, B, C, and D, which all implement a trait
Runnable.
trait Runnable {
fn run(&mut self);
}
impl Runnable for A {...}
impl Runnable for B {...}
impl ...
-1
votes
1
answer
103
views
Algorithm for Alternate merge strings in rust
Here is my code for alternate merge string in rust. I am not getting the expected output. It works fine for equal length strings. Issue is when we have unequal strings it skips one character.
impl ...
0
votes
1
answer
152
views
Getting a custom iterator to work in Rust over a &String
I am currently working on implementing a iterator which splits the given string and returns the substrings as an iterator. For a special character it is going to return just the special character or ...
0
votes
1
answer
256
views
Rust println! result is different that print! when using time::sleep [duplicate]
Ok, so I haven't worked with Rust for that long so sorry if this is dumb. But I'm trying to make a print function that takes in a string and then prints the string character by character on the same ...
0
votes
1
answer
113
views
split String twice and put it in a HashMap
I have a String atp.Status="draft";pureMM.maxOccurs="1";pureMM.minOccurs="1";xml.attribute="true" and want to split it twice and insert it into a HashMap. For ...
0
votes
0
answers
37
views
Rust &String to &str implicit conversion [duplicate]
Let's consider this code for my question
The playground link can be found here https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=400f59f484d86826de5829ba3f29fc89
fn ...
2
votes
1
answer
72
views
Why do I need of reference for the to_string function?
I am new to Rust. While trying to concatenate string literals and integers, I was given many errors because of the "to_string" function. After that realized that I needed to put a reference/...
3
votes
1
answer
60
views
Ensure an argument is a compile time defined string literal
In order to prevent risk of SQL injection, I would like to create an API with a function that only accepts compile time string literals as an inputs e.g. "SELECT * FROM MYTABLE;", "...
-1
votes
2
answers
210
views
Does Rust take up less memory when reading in UTF-8 file than python?
In https://stackoverflow.com/a/24542608/6629672 I found that Rust uses variable-length encoding for strings, which is why you can't easily index them. Python, on the other hand, uses a fixed length ...
1
vote
2
answers
792
views
`let` expressions in this position are unstable
I want to iterate over two strings in Rust. I read that it's not efficient to use indexes (nth() method). Thats why I am using iterators
fn main() {
let s1 = String::from("abacde");
...
1
vote
2
answers
627
views
Include newline in one-line raw string literal?
Constructing a string for bulk posting for the purposes of Elasticsearch, I need to conform to a particular newline formatting. A raw string literal like this does the job:
let json = format!(r#&...
0
votes
2
answers
1k
views
How do I split a string using multiple different characters as delimiters?
What is the most rusty/current way in (latest Rust) to do a basic and efficient string slit using multiple different possible split characters, i.e. convert:
"name, age. location:city"
into:...
0
votes
1
answer
50
views
Does Rust shadow variables that are not re-declared? [duplicate]
I am trying to learn Rust, and am trying to write a simple program that takes arguments from the command line, to get used to some basic concepts. The code I wrote to handle the arguments, fails, and ...
2
votes
2
answers
3k
views
Rust - idiomatic way to check if a string starts with one of a set of substrings
core::str
pub fn starts_with<'a, P>(&'a self, pat: P) -> bool
where
P: Pattern<'a>,
Returns true if the given pattern matches a prefix of this string slice.
Returns false if it ...
-3
votes
1
answer
130
views
how can i exit a loop in rust using a user input? [duplicate]
im trying to create a calculator with a that if the user writes that he doesnt want to do another operation it breaks it never does.
fn main {
loop {
// calculator code
println!("result: {}&...
0
votes
1
answer
139
views
What happens under the hood when String type gets casted to &str type in rust
To my understanding the String type is allocated on the heap in rust and the pointer and length of it on the stack. The &str type is allocated on the stack directly due to its fixed size.
Now if I ...
4
votes
2
answers
2k
views
Split string once on the first whitespace in Rust
I have a string, say "dog cat fish", that I want to split on the first whitespace into two slices that look like this: ("dog", "cat fish").
I tried to naively use the ...