Reputation: 95
I'm not entirely sure how to phrase my question, so I'll try and explain as best I can.
I'm trying to use Rust to write a UI for a program that runs in a terminal window. The program has two tabs, and my thought was to draw the sides of the tabs, get the length of that row, subtract 2 to get the correct placement for their name and insert the name, to get something like:
╭────────╮╭───────────╮
│ Lingon ││ Blueberry │
Unfortunately I can't subtract without the program panicking.
If I remove the subtraction and add a println! to see the length at the end of each tab, it correctly prints 4 and 14, but nevertheless incorrectly inserts the names at 2 and 10.
If I change the "\u{2502}
" to "l
" (lower case L) it "correctly" places them at the 4th and 14th place respectively.
I simplified the original code as much as I could and also added a rust playground link at the bottom.
fn main() {
let tab_names = vec!["Lingon", "Blueberry"];
let win_cols = 100;
let mut tab_rows = vec![String::with_capacity(win_cols); 2];
for name in tab_names {
tab_rows[0].push_str("\u{256d}");
tab_rows[0].push_str(&std::iter::repeat("\u{2500}").take(name.chars().count()+2).collect::<String>());
tab_rows[0].push_str("\u{256e}");
tab_rows[1].push_str("\u{2502}");
tab_rows[1].push_str(&std::iter::repeat("\u{0020}").take(2).collect::<String>());
tab_rows[1].push_str("\u{2502}");
let name_placement = tab_rows[1].chars().count();
println!("{}\r", name_placement);
tab_rows[1].insert_str(name_placement, name)
}
for i in 0..tab_rows.len() {
println!("{}\r", tab_rows[i]);
}
}
As I was editing my question before posting, I might have realized what the issue was.
I've attempted to answer it myself, but be advised that I'm not a programmer and might just make an even bigger fool of myself. If anyone who knows the answer can verify, It'd be greatly appreciated.
Upvotes: 1
Views: 199
Reputation: 95
A String is a string of characters, where each character may be represented by more than one byte. Like, for exampe, the '\u{2502}
' (vertical line) that I'm using, that is represented by three bytes.
The insert_str(n) method inserts strings at byte position n.
As I was trying to insert a String into a byte position that was inside a character, the program panicked.
Upvotes: 2