이러닝 플랫폼
Coddy GO 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 107개 중 105번째.
챌린지
쉬움course, student를 관리하고 learning progress를 추적하는 E-Learning Platform을 만들어 봅시다! structs, interfaces, composition, polymorphism을 결합하여 student가 course에 등록하고 lesson을 완료할 수 있는 일관된 system을 만들어 보세요.
code를 다섯 개의 file에 걸쳐 구성합니다:
lesson.go: individual learning unit을 나타내는Lessonstruct를 정의합니다. 각 lesson에는ID,Title,Duration(분 단위)이 있습니다. 포인터를 반환하는NewLessonconstructor를 포함합니다.course.go:ID,Title,Instructor, 그리고*Lesson포인터의 slice를 포함하는Coursestruct를 만듭니다.NewCourseconstructor와AddLessonmethod를 포함합니다. 또한 course의 모든 lesson duration의 합을 반환하는TotalDuration() intmethod를 구현합니다.student.go:ID,Name,Emailfield를 가진Studentstruct를 정의합니다.NewStudentconstructor를 포함합니다.enrollment.go: 이곳에서 progress tracking의 핵심 기능이 구현됩니다. student를 course에 연결하고 어떤 lesson이 완료되었는지 추적하는Enrollmentstruct를 만듭니다. 다음을 포함해야 합니다:Student에 대한 포인터Course에 대한 포인터CompletedLessonsmap (lesson ID에서 boolean으로 매핑)
Progress() float64method를 통해 percentage(0.0에서 100.0까지)를 반환하는Progressableinterface를 정의합니다.Enrollment에 다음 method를 구현합니다:
NewEnrollment(student *Student, course *Course) *Enrollment: 비어 있는 completed lesson map을 초기화하는 constructorCompleteLesson(lessonID string) string: lesson을 완료된 상태로 표시합니다. lesson이 course에 존재하지 않으면lesson not found, 이미 완료되었으면already completed, 성공하면completed를 반환합니다.Progress() float64: 완료된 lesson의 percentage(완료된 수/전체 수 * 100)를 반환하며, course에 lesson이 없으면 0.0을 반환합니다.
main.go: platform을 구성하고 enrollment operation을 처리합니다.course의 ID, title, instructor를 읽습니다. 그런 다음 lesson의 수와 각 lesson의 ID, title, duration을 읽습니다. student의 ID, name, email을 읽습니다. student를 course에 연결하는 enrollment를 생성합니다.
그런 다음 operation의 수를 읽습니다. 각 operation은
complete [lessonID]또는progress입니다. complete operation의 경우 result message를 출력합니다. progress operation의 경우 progress를 소수점 첫째 자리까지 format하고 percent sign을 뒤에 붙여 출력합니다.
다음 input이 제공됩니다:
- Course ID, Title, Instructor (3줄)
- lesson의 수, 이어서 각 lesson의 ID, Title, Duration (각각 3줄)
- Student ID, Name, Email (3줄)
- operation의 수, 이어서 각 operation (각각 1줄)
예를 들어 다음이 주어졌다고 합시다:
C001
Go Fundamentals
Jane Smith
3
L001
Variables
30
L002
Functions
45
L003
Structs
60
S001
Alice
alice@learn.com
5
progress
complete L001
progress
complete L001
complete L002출력은 다음과 같아야 합니다:
0.0%
completed
33.3%
already completed
completed그리고 다음이 주어졌다고 합시다:
C100
Python Basics
Bob Teacher
2
L100
Intro
20
L101
Loops
40
S100
Charlie
charlie@edu.com
4
complete L999
complete L100
complete L101
progress출력은 다음과 같아야 합니다:
lesson not found
completed
completed
100.0%Enrollment struct가 composition을 사용하여 student와 course를 서로 연결하는 한편, Progressable interface를 사용하면 어떤 type이든 completion status를 보고할 수 있다는 점에 주목하세요. 이 design은 확장하기 쉽습니다. 동일한 interface를 사용하여 individual lesson이나 전체 learning path에 progress tracking을 추가할 수도 있습니다!
직접 해보기
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
// 한 줄을 읽는 헬퍼 함수
readLine := func() string {
scanner.Scan()
return strings.TrimSpace(scanner.Text())
}
// 코스 정보 읽기
courseID := readLine()
courseTitle := readLine()
courseInstructor := readLine()
// TODO: NewCourse를 사용하여 코스 생성
_ = courseID
_ = courseTitle
_ = courseInstructor
// 레슨 수 읽기
numLessons, _ := strconv.Atoi(readLine())
// TODO: 각 레슨을 읽고 코스에 추가
for i := 0; i < numLessons; i++ {
lessonID := readLine()
lessonTitle := readLine()
lessonDuration, _ := strconv.Atoi(readLine())
// TODO: 레슨을 생성하고 코스에 추가
_ = lessonID
_ = lessonTitle
_ = lessonDuration
}
// 학생 정보 읽기
studentID := readLine()
studentName := readLine()
studentEmail := readLine()
// TODO: NewStudent를 사용하여 학생 생성
_ = studentID
_ = studentName
_ = studentEmail
// TODO: 학생을 코스에 연결하는 등록 생성
// 작업 수 읽기
numOps, _ := strconv.Atoi(readLine())
// 각 작업 처리
for i := 0; i < numOps; i++ {
operation := readLine()
if operation == "progress" {
// TODO: Progress()를 호출하고 "%.1f%%" 형식으로 출력
fmt.Println("0.0%") // 실제 진행률로 교체
} else if strings.HasPrefix(operation, "complete ") {
lessonID := strings.TrimPrefix(operation, "complete ")
// TODO: CompleteLesson을 호출하고 결과를 출력
_ = lessonID
fmt.Println("") // 실제 결과로 교체
}
}
}
객체 지향 프로그래밍의 모든 레슨
8에러 처리와 OOP
error 인터페이스사용자 정의 에러 타입에러 래핑 (fmt.Errorf)센티넬 에러errors.Is()와 errors.As()Panic, Defer, Recover요약 - 파일 파서직접 연습해 보세요: 온라인 Go 컴파일러