Решение на упр.04 задача 1 от Илиян Гаврилов

Обратно към всички решения

Към профила на Илиян Гаврилов

Резултати

  • 2 точки от тестове
  • 0 бонус точки
  • 2 точки общо
  • 2 успешни тест(а)
  • 0 неуспешни тест(а)

Код

#[derive(Debug)]
enum Spec {
SI,
IS,
KN,
I,
M
}
#[derive(Debug)]
enum Title {
Assistant,
Doctor,
Professor
}
#[derive(Debug)]
struct Student {
name: String,
age: u8,
spec: Spec
}
#[derive(Debug)]
struct Teacher {
name: String,
age: u8,
spec: Vec<Spec>,
title: Title
}
#[derive(Debug)]
struct University<T> {
name: String,
students: Vec<Student>,
teachers: Vec<T>
}
// ------------------------------
// Constructors
// ------------------------------
impl Student {
fn new(name: String, age: u8, spec: Spec) -> Self {
Student { name, age, spec }
}
}
impl Teacher {
fn new(name: String, age: u8, specs: Vec<Spec>, title: Title) -> Self {
Teacher { name, age, spec: specs, title }
}
}
impl<T> University<T> {
fn new(name: String, students: Vec<Student>, teachers: Vec<T>) -> Self {
University { name, students, teachers }
}
}
// ------------------------------
// ToJson Trait
// ------------------------------
trait ToJson {
fn to_json(&self) -> String;
}
fn escape_json_str(s: &str) -> String {
format!("\"{}\"", s
.replace('\\', "\\\\")
.replace('\"', "\\\"")
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t"))
}
impl ToJson for String {
fn to_json(&self) -> String {
escape_json_str(self)
}
}
impl ToJson for &str {
fn to_json(&self) -> String {
escape_json_str(self)
}
}
impl<T> ToJson for Option<T> where T: ToJson {
fn to_json(&self) -> String {
match self {
Some(val) => val.to_json(),
None => String::from("null"),
}
}
}
impl<T: ToJson> ToJson for Vec<T> {
fn to_json(&self) -> String {
let mut iter = self.iter();
let mut result = match iter.next() {
Some(first) => first.to_json(),
None => String::new(),
};
for e in iter {
result.push_str(", ");
result.push_str(&e.to_json());
}
format!("[{}]", result)
}
}
impl ToJson for Spec {
fn to_json(&self) -> String {
match self {
Spec::SI => "SI",
Spec::IS => "IS",
Spec::KN => "KN",
Spec::I => "I",
Spec::M => "M",
}.to_json()
}
}
impl ToJson for Title {
fn to_json(&self) -> String {
match self {
Title::Assistant => "Assistant",
Title::Doctor => "Doctor",
Title::Professor => "Professor"
}.to_json()
}
}
impl ToJson for Student {
fn to_json(&self) -> String {
format!("{{\"name\": {}, \"age\": {}, \"spec\": {}}}",
self.name.to_json(),
self.age,
self.spec.to_json()
)
}
}
impl ToJson for Teacher {
fn to_json(&self) -> String {
format!(
"{{\"name\": {}, \"age\": {}, \"spec\": {}, \"title\": {}}}",
self.name.to_json(),
self.age,
self.spec.to_json(),
self.title.to_json()
)
}
}
impl<T: ToJson> ToJson for University<T> {
fn to_json(&self) -> String {
format!(
"{{\"name\": {}, \"students\": {}, \"teachers\": {}}}",
self.name.to_json(),
self.students.to_json(),
self.teachers.to_json()
)
}
}
fn main() {
// Примерен университет
let student = Student {
name: "Ivan Petrov".to_string(),
age: 21,
spec: Spec::SI,
};
let teacher = Teacher {
name: "Maria Georgieva".to_string(),
age: 45,
spec: vec![Spec::SI, Spec::KN],
title: Title::Doctor,
};
let university = University {
name: "Sofia University".to_string(),
students: vec![student],
teachers: vec![teacher],
};
println!("{}", university.to_json());
// Може преподавателите да са от тип Teacher
let s1 = Student::new("Ivan".to_string(), 20, Spec::SI);
let s2 = Student::new("Peter".to_string(), 25, Spec::SI);
let t1 = Teacher::new(
"Dr. Petrov".to_string(),
45,
vec![Spec::SI, Spec::IS],
Title::Professor,
);
let uni = University::new("SU".to_string(), vec![s1, s2], vec![t1]);
println!("{}", uni.to_json());
// {
// "name":"SU",
// "students": [
// {"name": "Ivan", "age": 20, "spec": "SI"},
// {"name": "Peter", "age": 25, "spec": "SI"}
// ],
// "teachers": [
// {"name": "Dr. Petrov", "age": 45, "spec": ["SI", "IS"], "title": "Professor"}
// ]
// }
// Може и преподавателите да са от тип Student
let s1 = Student::new("Ivan".to_string(), 20, Spec::SI);
let s2 = Student::new("Peter".to_string(), 25, Spec::SI);
let uni = University::new("SU".to_string(), vec![s1], vec![s2]);
println!("{}", uni.to_json());
// {
// "name":"SU",
// "students": [
// {"name": "Ivan", "age": 20, "spec": "SI"}
// ],
// "teachers": [
// {"name": "Peter", "age": 25, "spec": "SI"}
// ]
// }
}

Лог от изпълнението

Updating crates.io index
     Locking 17 packages to latest compatible versions
   Compiling proc-macro2 v1.0.103
   Compiling unicode-ident v1.0.22
   Compiling quote v1.0.41
   Compiling futures-sink v0.3.31
   Compiling futures-core v0.3.31
   Compiling futures-channel v0.3.31
   Compiling memchr v2.7.6
   Compiling syn v2.0.109
   Compiling pin-utils v0.1.0
   Compiling futures-task v0.3.31
   Compiling slab v0.4.11
   Compiling futures-io v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling solution v0.1.0 (/tmp/d20251106-1757769-fb7j5i/solution)
warning: enum `Spec` is never used
 --> src/lib.rs:2:6
  |
2 | enum Spec {
  |      ^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: enum `Title` is never used
  --> src/lib.rs:11:6
   |
11 | enum Title {
   |      ^^^^^

warning: struct `Student` is never constructed
  --> src/lib.rs:18:8
   |
18 | struct Student {
   |        ^^^^^^^

warning: struct `Teacher` is never constructed
  --> src/lib.rs:25:8
   |
25 | struct Teacher {
   |        ^^^^^^^

warning: struct `University` is never constructed
  --> src/lib.rs:33:8
   |
33 | struct University<T> {
   |        ^^^^^^^^^^

warning: associated function `new` is never used
  --> src/lib.rs:43:6
   |
42 | impl Student {
   | ------------ associated function in this implementation
43 |   fn new(name: String, age: u8, spec: Spec) -> Self {
   |      ^^^

warning: associated function `new` is never used
  --> src/lib.rs:49:6
   |
48 | impl Teacher {
   | ------------ associated function in this implementation
49 |   fn new(name: String, age: u8, specs: Vec<Spec>, title: Title) -> Self {
   |      ^^^

warning: associated function `new` is never used
  --> src/lib.rs:55:6
   |
54 | impl<T> University<T> {
   | --------------------- associated function in this implementation
55 |   fn new(name: String, students: Vec<Student>, teachers: Vec<T>) -> Self {
   |      ^^^

warning: trait `ToJson` is never used
  --> src/lib.rs:64:7
   |
64 | trait ToJson {
   |       ^^^^^^

warning: function `escape_json_str` is never used
  --> src/lib.rs:68:4
   |
68 | fn escape_json_str(s: &str) -> String {
   |    ^^^^^^^^^^^^^^^

warning: function `main` is never used
   --> src/lib.rs:173:4
    |
173 | fn main() {
    |    ^^^^

warning: `solution` (lib) generated 11 warnings
   Compiling futures-macro v0.3.31
   Compiling futures-util v0.3.31
   Compiling futures-executor v0.3.31
   Compiling futures v0.3.31
warning: variants `KN`, `I`, and `M` are never constructed
 --> tests/../src/lib.rs:5:3
  |
2 | enum Spec {
  |      ---- variants in this enum
...
5 |   KN,
  |   ^^
6 |   I,
  |   ^
7 |   M
  |   ^
  |
  = note: `Spec` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
  = note: `#[warn(dead_code)]` on by default

warning: variants `Assistant` and `Doctor` are never constructed
  --> tests/../src/lib.rs:12:3
   |
11 | enum Title {
   |      ----- variants in this enum
12 |   Assistant,
   |   ^^^^^^^^^
13 |   Doctor,
   |   ^^^^^^
   |
   = note: `Title` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis

warning: function `main` is never used
   --> tests/../src/lib.rs:173:4
    |
173 | fn main() {
    |    ^^^^

warning: `solution` (test "solution_test") generated 3 warnings
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.41s
     Running tests/solution_test.rs (target/debug/deps/solution_test-8c2c5f784503f204)

running 2 tests
test solution_test::test_basic2 ... ok
test solution_test::test_basic ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

История (1 версия и 0 коментара)

Илиян качи първо решение на 31.10.2025 17:40 (преди около 1 месеца)