자기개발하는 QA
Rust 03 본문
고급 함수 정의
- 명시적인 수명 애너테이션
fn add_with_lifetimes<'a, 'b>(i: &'a i32, j: &'b i32) -> i32 {
*i + *j // <1>
}
fn main() {
let a = 10;
let b = 20;
let res = add_with_lifetimes(&a, &b); // <2>
println!("{}", res);
}
// 수명 매개 변수는 대부분 컴파일러가 자체적으로 추론하지만
// 명시적으로 프로그래머가 지정해 줄 수 있다.
fn main() {
let a = 10;
println!("{}", &a);
}
// &는 c의 포인터와 다르다 주소가 아닌 값을 인쇄한다.
제네릭 함수
use std::ops::{Add}; // <1>
use std::time::{Duration}; // <2>
fn add<T: Add<Output = T>>(i: T, j: T) -> T { // <3>
i + j
}
fn main() {
let floats = add(1.2, 3.4); // <4>
let ints = add(10, 20); // <5>
let durations = add( // <6>
Duration::new(5, 0), // <6>
Duration::new(10, 0) // <6>
);
println!("{}", floats);
println!("{}", ints);
println!("{:?}", durations); // <7>
}
// <3> 트레이드 제약을 포함해야 사용할 수 있다. (인터페이스, 프로토콜, 계약)
grep-lite
fn main() {
let search_term = "picture";
// let search_term = String::from("window");
// 요렇게 String 으로 선언 가능 다만 &search_term 써야한다.
let quote = "\
Every face, every shop, bedroom window, public-house, and
dark square is a picture feverishly turned--in search of what?
It is the same with books.
What do we seek through millions of pages?"; // <1>
for line in quote.lines() { // <2>
if line.contains(search_term) {
println!("{}", line);
}
}
}
배열, 슬라이스, 벡터
fn main() {
let arr = [1, 2, 3]; // 배열
let vec = vec![1, 2, 3]; // 벡터
let int_slice = &vec[..]; // 슬라이스 백터
let str_slice: &[&str] = &["one", "two", "three"]; // 슬라이스
println!("{:?}", arr);
println!("{:?}", int_slice);
println!("{:?}", str_slice);
}
서드파티 코드
$ cargo add XX
// 의존성 추가
$ cargo doc
// doc/{project_name}/index.html
$ cargo doc --open
// 열어보기
$ rustup
// 툴체인 관리
명령형 인자 지원 / 파일 읽어 드리기 / 표준 입력에서 읽기
use ::clap::{App, Arg}; // Brings clap::app and clap::Arg objects into local scope
use ::regex::Regex;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
fn main() {
// 명령형 인자 지원
let args = App::new("grep-lite")
.version("0.1")
.about("searches for patterns")
.arg(
Arg::with_name("pattern")
.help("The pattern to search for.")
.takes_value(true)
.required(true),
)
.arg(
Arg::with_name("input")
.help("File to search.")
.takes_value(true)
.required(false),
)
.get_matches();
let pattern = args.value_of("pattern").unwrap(); // Extracts the pattern argument
let input = args.value_of("input").unwrap_or("-");
let re = Regex::new(pattern).unwrap();
if input == "-" {
// 표준 입력에서 읽기
let stdin = io::stdin();
let reader = stdin.lock();
process_lines(reader, re);
} else {
// 파일 읽어 드리기
let file = File::open(input).unwrap();
let reader = BufReader::new(file);
process_lines(reader, re);
}
}
fn process_lines<T: BufRead + Sized>(reader: T, re: Regex) {
for line_result in reader.lines() {
let line = line_result.unwrap();
// line is a String, but re.find() takes an &str as an argument
match re.find(&line) {
Some(_) => println!("{}", line),
None => (),
}
}
}
728x90