본문 바로가기
프로그램 개발(분석, 설계, 코딩, 배포)/100. 기타

rust println

by 3604 2024. 6. 15.
728x90

println는 Display 트레잇을 구현한 타입만을 받도록 정의돼있다.
이제까지 쓴 정수나 문자열 등도 전부 저걸 구현하고 있었던 것이다...

먼저 이름과 나이를 갖는 간단한 타입 Person을 정의했다.
struct Person
{
     name: String,
     age: i32
}

이에 대한 Display를 구현해보자.

Display에는 fmt라는 메서드가 하나 있다.
이 메서드에선 포매터를 받아다가 그 write 매크로로 포매터에 출력할 문자열을 쓰고 반환한다.

impl std::fmt::Display for Person
{
     fn fmt(&self, formatter:&mut std::fmt::Formatter)->std::fmt::Result
    {
          write!(formatter, "이름:{} 나이:{}", self.name, self.age)
     }
}

println에서 내부적으로 포매터를 보내고 결과값을 받아다 출력문에 이어붙이는듯하다.

그럼 이제 출력이 잘 될 것이다.
fn main()
{
     let john =
 ㅤPerson{name:"john".to_string(), age:23};
 
     println!("{}",john);
}

 
 
 

 

Println. In Rust we print values to the console with the "println!" macro. This is the easiest way to output data—but faster approaches are available.
In Rust, each println invocation will have overhead as it locks the underlying implementation. If we group together output lines, we can improve performance.
stdin
format
Console Color
 
Println example. In this program we see the basic syntax for the println macro. It is important to include the exclamation mark at the end.
Version 1 We place the variable name from the surrounding block in between the braces in the println argument.
Version 2 We use separate arguments after empty braces. With this syntax, we can call functions or use more complex expressions.
fn main() { // Version 1: Print some content to the console. let count = 300; let value = "friend"; println!("Hello {value}: {count}"); // Version 2: Can use arguments instead. // Arguments can be more complex expressions. println!("Hello {}: {}", value, count + 1); }Hello friend: 300 Hello friend: 301
728x90