일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- fluent python
- docker
- function
- Fast API
- BAEKJOON
- Algorithm
- Thread
- Network
- IMAGE
- 플랫폼
- 전문가를 위한 파이썬
- 백준
- AWS
- 코어 이더리움 프로그래밍
- guru
- Kubernetes
- Ethereum
- 알고리즘
- RabbitMQ
- 러스트
- 블록체인
- 동시성
- 이더리움
- Python
- 파이썬
- dockerfile
- rust
- Container
- Refactoring
- BlockChain
Archives
- Today
- Total
글쓰기 | 방명록 | 관리 |
Victoree's Blog
[Code] Struct & Enum 연습문제 본문
728x90
뭐 해답은 따로 있지만,, 그냥 기록용.. :)
// TODO: 구현이 완료되면 아래 줄은 삭제합니다.
#![allow(unused_variables, dead_code)]
struct User {
name: String,
age: u32,
weight: f32,
}
impl User {
pub fn new(name: String, age: u32, weight: f32) -> Self {
User{name, age, weight}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn age(&self) -> u32 {
self.age
}
pub fn weight(&self) -> f32 {
self.weight
}
pub fn set_age(&mut self, new_age: u32) {
self.age = new_age;
}
pub fn set_weight(&mut self, new_weight: f32) {
self.weight = new_weight;
}
}
fn main() {
let bob = User::new(String::from("Bob"), 32, 155.2);
println!("I'm {} and my age is {}", bob.name(), bob.age());
}
#[test]
fn test_weight() {
let bob = User::new(String::from("Bob"), 32, 155.2);
assert_eq!(bob.weight(), 155.2);
}
#[test]
fn test_set_age() {
let mut bob = User::new(String::from("Bob"), 32, 155.2);
assert_eq!(bob.age(), 32);
bob.set_age(33);
assert_eq!(bob.age(), 33);
}
2. Polygon 구조체
// TODO: remove this when you're done with your implementation.
#![allow(unused_variables, dead_code)]
#[derive(Debug, Copy, Clone)]
pub struct Point {
x: i32,
y: i32
}
impl Point {
pub fn new(x: i32, y: i32) -> Self {
Point{x,y}
}
pub fn magnitude(self) -> f64 {
f64::from(self.x.pow(2) + self.y.pow(2)).sqrt()
}
pub fn dist(self, p: Point) -> f64 {
(self-p).magnitude()
}
}
impl std::ops::Add for Point {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self {
x: self.x+other.x,
y: self.y+other.y
}
}
}
impl std::ops::Sub for Point {
type Output = Self;
fn sub(self, other: Self) -> Self::Output {
Self {
x: self.x-other.x,
y: self.y-other.y
}
}
}
impl std::cmp::PartialEq for Point {
fn eq(&self, other: &Self) -> bool {
self.x == other.x && self.y == other.y
}
}
pub struct Polygon {
points: Vec<Point>,
}
impl Polygon {
pub fn new() -> Polygon {
Polygon {points: Vec::new()}
}
pub fn add_point(&mut self, point: Point) {
self.points.push(point);
}
pub fn left_most_point(&self) -> Option<Point> {
self.points.iter().min_by_key(|p| p.x).copied()
}
pub fn iter(&self) -> impl Iterator<Item = &Point> {
self.points.iter()
}
pub fn length(&self) -> f64 {
let mut length = 0.0;
if self.points.is_empty() { return length; }
let mut start_point = self.points[0];
for point in &self.points[1..] {
length += point.dist(start_point);
start_point = *point;
}
length += start_point.dist(self.points[0]);
length
}
}
pub struct Circle {
center: Point,
radius: u32
}
impl Circle {
pub fn new(center: Point, radius: u32) -> Circle {
Circle {center, radius}
}
pub fn circumference(&self) -> f64 {
2.0 * std::f64::consts::PI * f64::from(self.radius)
}
}
pub enum Shape {
Polygon(Polygon),
Circle(Circle),
}
impl From<Polygon> for Shape {
fn from(poly: Polygon) -> Self {
Shape::Polygon(poly)
}
}
impl From<Circle> for Shape {
fn from(circle: Circle) -> Self {
Shape::Circle(circle)
}
}
impl Shape {
pub fn perimeter(&self) -> f64 {
match self {
Shape::Polygon(poly) => {poly.length()}
Shape::Circle(circle) => {circle.circumference()}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn round_two_digits(x: f64) -> f64 {
(x * 100.0).round() / 100.0
}
#[test]
fn test_point_magnitude() {
let p1 = Point::new(12, 13);
assert_eq!(round_two_digits(p1.magnitude()), 17.69);
}
#[test]
fn test_point_dist() {
let p1 = Point::new(10, 10);
let p2 = Point::new(14, 13);
assert_eq!(round_two_digits(p1.dist(p2)), 5.00);
}
#[test]
fn test_point_add() {
let p1 = Point::new(16, 16);
let p2 = p1 + Point::new(-4, 3);
assert_eq!(p2, Point::new(12, 19));
}
#[test]
fn test_polygon_left_most_point() {
let p1 = Point::new(12, 13);
let p2 = Point::new(16, 16);
let mut poly = Polygon::new();
poly.add_point(p1);
poly.add_point(p2);
assert_eq!(poly.left_most_point(), Some(p1));
}
#[test]
fn test_polygon_iter() {
let p1 = Point::new(12, 13);
let p2 = Point::new(16, 16);
let mut poly = Polygon::new();
poly.add_point(p1);
poly.add_point(p2);
let points = poly.iter().cloned().collect::<Vec<_>>();
assert_eq!(points, vec![Point::new(12, 13), Point::new(16, 16)]);
}
#[test]
fn test_shape_perimeters() {
let mut poly = Polygon::new();
poly.add_point(Point::new(12, 13));
poly.add_point(Point::new(17, 11));
poly.add_point(Point::new(16, 16));
let shapes = vec![
Shape::from(poly),
Shape::from(Circle::new(Point::new(10, 20), 5)),
];
let perimeters = shapes
.iter()
.map(Shape::perimeter)
.map(round_two_digits)
.collect::<Vec<_>>();
assert_eq!(perimeters, vec![15.48, 31.42]);
}
}
#[allow(dead_code)]
fn main() {}
728x90
'Rust' 카테고리의 다른 글
[6] 표준 라이브러리 [Option, Result, Box, Cons List, Rc<T>] (0) | 2023.03.02 |
---|---|
[5] 흐름제어 [for, loop, while ...] (0) | 2023.03.02 |
[4] 구조체(Struct)와 열거형(Enum) (0) | 2023.02.23 |
[3] 라이프 타임과 참조자 유효화 (0) | 2023.02.16 |
[2] Rust의 꽃 : Memory Management와 Ownership (0) | 2023.02.16 |
Comments