-
Rust]❤️심도깊게(String &str& 'static str&❤️Converts a slice of bytes)❤️to_string(),⭐️cow코딩Coding/Rust❤️Optimization❤️ 2022. 4. 17. 21:02728x90
string 만드는 방법fn main { let string_1 = String::from("Hello there"); // From trait let string_2 = "Hello there".to_string(); // Display trait let string_3: String = "Hello there".into(); // From let string_4 = "Hello there".to_owned(); // ToOwned trait. str -> String // str -> String }
String Slices
https://doc.rust-lang.org/book/ch04-03-slices.htmlThe Slice Type - The Rust Programming Language
Slices let you reference a contiguous sequence of elements in a collection rather than the whole collection. A slice is a kind of reference, so it does not have ownership. Here’s a small programming problem: write a function that takes a string and retur
doc.rust-lang.org
Function std::str::from_utf8
use std::str; // some bytes, in a vector let sparkle_heart = vec![240, 159, 146, 150]; // We know these bytes are valid, so just use `unwrap()`. let sparkle_heart = str::from_utf8(&sparkle_heart).unwrap(); assert_eq!("💖", sparkle_heart);
https://doc.rust-lang.org/std/str/fn.from_utf8.htmlfrom_utf8 in std::str - Rust
Converts a slice of bytes to a string slice. A string slice (&str) is made of bytes (u8), and a byte slice (&[u8]) is made of bytes, so this function converts between the two. Not all byte slices are valid string slices, however: &str requires that it is v
doc.rust-lang.org
easy rust Kor116 - Cow again
3분 53초에 나옴
https://youtu.be/yvrRv1dUmLItype 알아보기
any을 활용하여 타입을 알수 있다
rust에서 타입type_of을 알아보는 방법ex:String의 타입 알아보기 -
https://economiceco.tistory.com/m/13349rust에서 타입type_of을 알아보는 방법ex:String의 타입 알아보기
~/Documents/Project/Github/rust_project/training_rustacean_rust/src/main.rs.html 1 use std::any::type_name; 2 3 fn type_of<T>(_: T) -> &'static str { 4 type_name::<T>() 5 } 6 7 fn main() { 8 let my_..
economiceco.tistory.com
Rust push String bytes to Vec (u8)Add the bytes from a string to a u8 vector, merging strings together in a byte Vec.
https://www.dotnetperls.com/push-u8-vec-rust
Rust push String bytes to Vec (u8) - Dot Net Perls
Append_string This function is called with 2 arguments. In the program, we see that it appends the bytes from the strings to the vector.
www.dotnetperls.com
Storing UTF-8 Encoded Text with Strings
https://doc.rust-lang.org/book/ch08-02-strings.html
Storing UTF-8 Encoded Text with Strings - The Rust Programming Language
We talked about strings in Chapter 4, but we’ll look at them in more depth now. New Rustaceans commonly get stuck on strings for a combination of three reasons: Rust’s propensity for exposing possible errors, strings being a more complicated data struc
doc.rust-lang.org
https://users.rust-lang.org/t/to-string-vs-to-owned-for-string-literals/1441`to_string()` vs `to_owned()` for string literals
I’ve seen both to_string() and to_owned() used for converting a string literal into a String. What are the differences between these two options, and when should you use which one?
users.rust-lang.org
easy_rust
프로그래밍 언어 러스트를 배웁시다! 014 Easy Rust in Korean: String and &str
프로그래밍 언어 러스트를 배웁시다! 015 Easy Rust in Korean: String methods
const and static
https://youtu.be/E48iJShSi7s
밑에 내용이 정리 완결판!!
What is the most idiomatic way to convert a &str to a String?
Some options are:
https://users.rust-lang.org/t/what-is-the-idiomatic-way-to-convert-str-to-string/12160/5What is the idiomatic way to convert &str to String?
johnthagen August 1, 2017, 10:35pm #1 What is the most idiomatic way to convert a &str to a String? Some options are: 13 Likes stusmall August 1, 2017, 10:37pm #2 I use String::from for static strings and to_owned() for others, but I’ve never thought har
users.rust-lang.org
String 자세히
공식 Rust ebook
https://doc.rust-lang.org/1.30.0/book/second-edition/ch08-02-strings.htmlStrings - The Rust Programming Language
We talked about strings in Chapter 4, but we’ll look at them in more depth now. New Rustaceans commonly get stuck on strings for a combination of three reasons: Rust’s propensity for exposing possible errors, strings being a more complicated data struc
doc.rust-lang.org
심도 깊게 들어감 스택 vs힙 비교하면서
https://bes.github.io/blog/rust-strings/
Strings in Rust
14 March 2021 · reading time 10 minutes rust programming heap stack string During the last 20 years I have used a number of garbage collected and reference counted programming languages. All of them have a single type for representing strings. Rust has tw
bes.github.io
❤️ Stack
It's possible to store string data on the stack, one way would be to create an array of u8 and then get a &str slice pointing into that array.
This is stolen from the str documentation:
https://doc.rust-lang.org/std/str/fn.from_utf8.htmlfrom_utf8 in std::str - Rust
Converts a slice of bytes to a string slice. A string slice (&str) is made of bytes (u8), and a byte slice (&[u8]) is made of bytes, so this function converts between the two. Not all byte slices are valid string slices, however: &str requires that it is v
doc.rust-lang.org
bytes 기본 개념❤️ 무조건 암기!!
Converts a slice of bytes to a string slice.
A string slice (&str) is made of bytes (u8), and a byte slice (&[u8]) is made of bytes, so this function converts between the two.
https://doc.rust-lang.org/std/str/fn.from_utf8.htmlfrom_utf8 in std::str - Rust
Converts a slice of bytes to a string slice. A string slice (&str) is made of bytes (u8), and a byte slice (&[u8]) is made of bytes, so this function converts between the two. Not all byte slices are valid string slices, however: &str requires that it is v
doc.rust-lang.org
bytes 개념 심도 깊게
https://doc.servo.org/bytes/struct.Bytes.html
Bytes in bytes - Rust
Splits the slice into a slice of N-element arrays, starting at the beginning of the slice, and a remainder slice with length strictly less than N. Panics if N is 0. This check will most probably get changed to a compile time error before this method gets s
doc.servo.org
Rust] From and Into
https://doc.rust-lang.org/rust-by-example/conversion/from_into.htmlFrom and Into - Rust By Example
The From and Into traits are inherently linked, and this is actually part of its implementation. If you are able to convert type A from type B, then it should be easy to believe that we should be able to convert type B to type A. The From trait allows for
doc.rust-lang.org
https://users.rust-lang.org/t/what-is-the-idiomatic-way-to-convert-str-to-string/12160What is the idiomatic way to convert &str to String?
What is the most idiomatic way to convert a &str to a String? Some options are: "hello".to_owned() "hello".to_string() String::from("hello") format!("hello")
users.rust-lang.org
ToSting
https://doc.rust-lang.org/nightly/std/string/trait.ToString.htmlToString in std::string - Rust
In this implementation, the to_string method panics if the Display implementation returns an error. This indicates an incorrect Display implementation since fmt::Write for String never returns an error itself.
doc.rust-lang.org
ToOwned
Uses borrowed data to replace owned data
(cow, clone에서 주로 씀)
https://doc.rust-lang.org/nightly/std/borrow/trait.ToOwned.htmlToOwned in std::borrow - Rust
Uses borrowed data to replace owned data, usually by cloning. This is borrow-generalized version of Clone::clone_from. Basic usage: let mut s: String = String::new(); "hello".clone_into(&mut s); let mut v: Vec = Vec::new(); [1, 2][..].clone_into(&mut v); R
doc.rust-lang.org
⭐️⭐️⭐️⭐️⭐️⭐️👍
cow는 실전에서도 많이 쓰고
smart pointer 라 빠르니 별표 백만개 중요cow의 장점(easy_rust119,120)
1. Reference를 그대로 쓸 수 있다
2. owned타입을 가지거나 owned타입으로 바꿔서 데이타를 바꿀 수 있다3. 데이터를 바꿀 수 있다(easy_rust120)
4. 메모리를 안 쓰고 borrow하기 때문에 겁나게 빠르다 ㅎㅎ
대박!!
5. to_mut().push('!')
하면 수정할 수 없는 Reference를 수정 할 수 있다 &mut
owned타입으로 바꾼 후 데이터 수정
(easy_rust120)
⭐️Cow = Clone on write❤️
Memory allocation이 필요없다⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
Rust연습] cow_빨라서 최고borrow에서 적극 활용하자 -
https://economiceco.tistory.com/m/13340Rust연습] cow_빨라서 최고borrow에서 적극 활용하자
~/Documents/Project/Github/rust_project/training_rustacean_rust/src/main.rs.html 1 use std::borrow::Cow; 2 3 #[derive(Debug)] 4 struct User<'a> { 5 name: Cow<'a, str>, 6 } 7 8 fn main() { 9 let name..
economiceco.tistory.com
cow 연결 blanket implementations
cow가 deref로 연결 됨 ㅎㅎ 대박
cow에서 trait implementations
Add<&'a str>
AddAssign<Cow<'a, str>>
연결해서 공부 하면 됨
(easy-rust121~)
+ Add
- Sub
+= (AddAssign)
5분56초
blanket implementations 개념
https://youtu.be/yvrRv1dUmLI
deref
117,118보면 됨
https://youtu.be/tFC8ZWvMDOE
ToOwned는 Associated type이다
https://doc.rust-lang.org/rust-by-example/generics/assoc_items/types.htmlAssociated types - Rust By Example
The use of "Associated types" improves the overall readability of code by moving inner types locally into a trait as output types. Syntax for the trait definition is as follows: #![allow(unused)] fn main() { // `A` and `B` are defined in the trait via the
doc.rust-lang.org
공식 문서에서 보라색 글씨는 trait라는 뜻
그래서 ToOwned는 trait
연관 타입(associated type)은 타입 자리지정자(type placeholder)를 트레이트와 연결하며 이 자리 지정자 타입을 사용해 트레이트의 메서드 시그니처를 정의할 수 있다
Rust 공식책518p참조
cow part1
https://youtu.be/3HgcxuO_f8c
Cow part2
https://youtu.be/yvrRv1dUmLI
part 3
https://youtu.be/1UrSBfjZaU0
ToOwned
예시
https://youtu.be/C48MN4d8I5Y
Rust) shared reference
❤️ unique reference- https://economiceco.tistory.com/m/14001
Rust) shared reference ❤️ unique reference
shared reference unique reference https://youtu.be/Bfqx_V2gp1Y
economiceco.tistory.com
반응형'코딩Coding > Rust❤️Optimization❤️' 카테고리의 다른 글
Rust❤️Design Patterns -eBook (0) 2022.04.26 rust concurrency) Rayon (0) 2022.04.26 Rust] borrow가 있다면 일반 String보다 빠르다.Cow최고 (0) 2022.04.19 Rust]❤️All Algorithm implemented in Rust (0) 2022.04.18 러스트Rust] Compile컴파일_시간은 늘어나지만 실행 속도 올리는 최적화Optimization (0) 2022.04.08 Reliable optimization for idiomatic Rust- Ferrous System Gmbh(cargo miri) (0) 2022.04.04 Rust]cargo nextest run(일반 test보다 60프로 이상 더 빠름) (0) 2022.03.23 rust컴파일 속도 더 빠르게 만들기zld(# `brew install michaeleisel/zld/zld` (0) 2022.03.17