mirror of
https://github.com/MADTeacher/go_basics.git
synced 2025-11-23 21:34:47 +02:00
отредактирована 3 глава
This commit is contained in:
16
part_3/3.1/1.go
Normal file
16
part_3/3.1/1.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
departmentName string
|
||||
age uint8
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
var emp employee
|
||||
emp2 := employee{}
|
||||
fmt.Println(emp, emp2) // { 0 } { 0 }
|
||||
}
|
||||
20
part_3/3.1/10.go
Normal file
20
part_3/3.1/10.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type point struct {
|
||||
x int
|
||||
y int
|
||||
}
|
||||
|
||||
func checkOutput(first, second int, check bool) {
|
||||
fmt.Printf("point%d == point%d - %t\n", first, second, check)
|
||||
}
|
||||
|
||||
func main() {
|
||||
point1 := point{10, 20}
|
||||
point2 := point{10, 20}
|
||||
point3 := point{x: 2, y: 43}
|
||||
checkOutput(1, 2, point1 == point2)
|
||||
checkOutput(2, 3, point2 == point3)
|
||||
}
|
||||
21
part_3/3.1/11.go
Normal file
21
part_3/3.1/11.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type point struct {
|
||||
x int
|
||||
y int
|
||||
}
|
||||
|
||||
type shape struct {
|
||||
name string
|
||||
center point
|
||||
}
|
||||
|
||||
func main() {
|
||||
myShape := shape{
|
||||
name: "Cube",
|
||||
center: point{x: 10, y: 6},
|
||||
}
|
||||
fmt.Printf("%+v\n", myShape) // {name:Cube center:{x:10 y:6}}
|
||||
}
|
||||
26
part_3/3.1/2.go
Normal file
26
part_3/3.1/2.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
departmentName string
|
||||
age uint8
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp1 := employee{
|
||||
name: "Alex",
|
||||
age: 25,
|
||||
departmentName: "R&D",
|
||||
position: "Assistant",
|
||||
}
|
||||
emp2 := employee{
|
||||
name: "Tom",
|
||||
position: "Intern",
|
||||
}
|
||||
|
||||
fmt.Println(emp1) // {Alex R&D 25 Assistant}
|
||||
fmt.Println(emp2) // {Tom 0 Intern}
|
||||
}
|
||||
3
part_3/3.1/3.1.7/golang/factory/go.mod
Normal file
3
part_3/3.1/3.1.7/golang/factory/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module golang/factory
|
||||
|
||||
go 1.24
|
||||
22
part_3/3.1/3.1.7/golang/factory/main.go
Normal file
22
part_3/3.1/3.1.7/golang/factory/main.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang/factory/shape"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
myShape := shape.Shape{
|
||||
Name: "Cube",
|
||||
Center: shape.Point{X: 4, Y: 5},
|
||||
}
|
||||
|
||||
myShape1 := shape.Shape{"Triangle", shape.Point{1, 9}}
|
||||
|
||||
fmt.Printf("%+v\n", myShape) // {Name:Cube Center:{X:4 Y:5}}
|
||||
fmt.Printf("%+v\n", myShape1) // {Name:Triangle Center:{X:1 Y:9}}
|
||||
myShape.Center.Y = 2
|
||||
myShape.Name = "Circle"
|
||||
fmt.Printf("%+v\n", myShape) // {Name:Circle Center:{X:4 Y:2}}
|
||||
}
|
||||
11
part_3/3.1/3.1.7/golang/factory/shape/shape.go
Normal file
11
part_3/3.1/3.1.7/golang/factory/shape/shape.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package shape
|
||||
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
|
||||
type Shape struct {
|
||||
Name string
|
||||
Center Point
|
||||
}
|
||||
17
part_3/3.1/3.go
Normal file
17
part_3/3.1/3.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
departmentName string
|
||||
age uint8
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp3 := employee{"Alex", "R&D", 25, "Assistant"} // ok
|
||||
// emp3 := employee{"Alex", "R&D"} – ошибка!!!
|
||||
|
||||
fmt.Println(emp3) // {Alex R&D 25 Assistant}
|
||||
}
|
||||
22
part_3/3.1/4.go
Normal file
22
part_3/3.1/4.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
departmentName string
|
||||
age uint8
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp2 := employee{
|
||||
name: "Tom",
|
||||
position: "Intern",
|
||||
}
|
||||
emp2.age = 22
|
||||
emp2.departmentName = "R&D"
|
||||
fmt.Println(emp2) // {Tom R&D 22 Intern}
|
||||
emp2.position = "Engineer"
|
||||
fmt.Println(emp2) // {Tom R&D 22 Engineer}
|
||||
}
|
||||
22
part_3/3.1/5.go
Normal file
22
part_3/3.1/5.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
departmentName string
|
||||
age uint8
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp2 := employee{
|
||||
name: "Tom",
|
||||
position: "Intern",
|
||||
}
|
||||
emp2.age = 22
|
||||
emp2.departmentName = "R&D"
|
||||
fmt.Printf("%+v\n", emp2) // {name:Tom departmentName:R&D age:22 position:Intern}
|
||||
emp2.position = "Engineer"
|
||||
fmt.Printf("%+v\n", emp2) // {name:Tom departmentName:R&D age:22 position:Engineer}
|
||||
}
|
||||
22
part_3/3.1/6.go
Normal file
22
part_3/3.1/6.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
departmentName string
|
||||
age uint8
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp2 := employee{
|
||||
name: "Tom",
|
||||
position: "Intern",
|
||||
}
|
||||
emp2.age = 22
|
||||
emp2.departmentName = "R&D"
|
||||
fmt.Printf("%+v\n", emp2.age) // 22
|
||||
employeeAge := emp2.age
|
||||
fmt.Println(employeeAge) // 22
|
||||
}
|
||||
38
part_3/3.1/7.go
Normal file
38
part_3/3.1/7.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
departmentName string
|
||||
age uint8
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp2 := employee{
|
||||
name: "Tom",
|
||||
position: "Intern",
|
||||
}
|
||||
empPoint := &emp2 // первый способ через оператор &
|
||||
empPoint1 := &employee{ // второй способ через оператор &
|
||||
name: "Maxim",
|
||||
position: "Intern",
|
||||
age: 18,
|
||||
}
|
||||
// изменение значений полей через указатель на структуру
|
||||
(*empPoint).departmentName = "R&D"
|
||||
// тоже самое, что
|
||||
empPoint.age = 23
|
||||
empPoint1.departmentName = "R&D"
|
||||
fmt.Printf("%+v\n", *empPoint) // {name:Tom departmentName:R&D age:23 position:Intern}
|
||||
fmt.Printf("%+v\n", *empPoint1) // {name:Maxim departmentName:R&D age:18 position:Intern}
|
||||
|
||||
empPoint2 := new(employee) // использование ключевого слова new
|
||||
fmt.Printf("%+v\n", *empPoint2) // {name: departmentName: age:0 position:}
|
||||
empPoint2.departmentName = "Oo"
|
||||
empPoint2.name = "Alex"
|
||||
empPoint2.position = "Engineer"
|
||||
empPoint2.age = 40
|
||||
fmt.Printf("%+v\n", *empPoint2) // {name:Alex departmentName:Oo age:40 position:Engineer}
|
||||
}
|
||||
29
part_3/3.1/8.go
Normal file
29
part_3/3.1/8.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
string // первое анонимное поле
|
||||
uint8 // второе анонимное поле
|
||||
position string
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp := employee{
|
||||
name: "Tom",
|
||||
position: "Intern",
|
||||
}
|
||||
emp1 := employee{
|
||||
name: "Alex",
|
||||
position: "Intern",
|
||||
uint8: 17,
|
||||
string: "R&D",
|
||||
}
|
||||
// присваиваем значение анонимному полю
|
||||
emp.uint8 = 22
|
||||
emp.string = "R&D"
|
||||
fmt.Printf("%+v\n", emp1) //{name:Alex string:R&D uint8:17 position:Intern}
|
||||
fmt.Printf("%+v\n", emp) // {name:Tom string:R&D uint8:22 position:Intern}
|
||||
fmt.Printf("%+v\n", emp.uint8) // 22 - вывод значения анонимного поля
|
||||
}
|
||||
34
part_3/3.1/9.go
Normal file
34
part_3/3.1/9.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type employee struct {
|
||||
name string
|
||||
age uint8
|
||||
}
|
||||
|
||||
func valueFunc(emp employee) {
|
||||
emp.name = "O_O"
|
||||
fmt.Printf("Copy value: %+v\n", emp)
|
||||
}
|
||||
|
||||
func pointFunc(emp *employee) {
|
||||
emp.name = "^_^"
|
||||
fmt.Printf("Point to value: %+v\n", emp)
|
||||
}
|
||||
|
||||
func main() {
|
||||
emp := employee{
|
||||
name: "Tom",
|
||||
age: 45,
|
||||
}
|
||||
newEmployee := emp
|
||||
newEmployee.age = 22
|
||||
fmt.Printf("newEmployee = %+v\n", newEmployee)
|
||||
fmt.Printf("emp = %+v\n", emp)
|
||||
|
||||
valueFunc(emp) // передача в функцию по значению
|
||||
fmt.Printf("emp = %+v\n", emp)
|
||||
pointFunc(&emp) // передача в функцию по указателю
|
||||
fmt.Printf("emp = %+v\n", emp)
|
||||
}
|
||||
21
part_3/3.10/1.go
Normal file
21
part_3/3.10/1.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func SumInt(a, b int) int {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func SumFloat(a, b float64) float64 {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func SumString(a, b string) string {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(SumFloat(10.3, 45.1)) // 55.4
|
||||
fmt.Println(SumInt(10, 45)) // 55
|
||||
fmt.Println(SumString("^_", "^")) // ^_^
|
||||
}
|
||||
24
part_3/3.10/10.go
Normal file
24
part_3/3.10/10.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func CreateNewMap[K comparable, V any](k []K, v *[]V) *map[K]V {
|
||||
// создание словаря из среза и указателя на срез
|
||||
newMap := make(map[K]V)
|
||||
if len(k) < len(*v) {
|
||||
for idx, elem := range k {
|
||||
newMap[elem] = (*v)[idx]
|
||||
}
|
||||
} else {
|
||||
for idx, elem := range *v {
|
||||
newMap[k[idx]] = elem
|
||||
}
|
||||
}
|
||||
return &newMap
|
||||
}
|
||||
|
||||
func main() {
|
||||
intSlice := []int{1, 3, 4, 6, 7}
|
||||
stringSlice := []string{"Oo", "^_^", "-_-"}
|
||||
fmt.Println(CreateNewMap(intSlice, &stringSlice)) // &map[1:Oo 3:^_^ 4:-_-]
|
||||
}
|
||||
13
part_3/3.10/2.go
Normal file
13
part_3/3.10/2.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func Sum[T int | float64 | string](a, b T) T {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println(Sum(10.3, 45.1)) // 55.4
|
||||
fmt.Println(Sum(10, 45)) // 55
|
||||
fmt.Println(Sum("^_", "^")) // ^_^
|
||||
}
|
||||
16
part_3/3.10/3.go
Normal file
16
part_3/3.10/3.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type MyInt int
|
||||
|
||||
func Sum[T int | float64 | string](a, b T) T {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func main() {
|
||||
var value1, value2 MyInt = 34, 22
|
||||
fmt.Println(Sum(value1, value2))
|
||||
// MyInt does not implement int|float64|string
|
||||
// (possibly missing ~ for int in constraint int|float64|string)
|
||||
}
|
||||
14
part_3/3.10/4.go
Normal file
14
part_3/3.10/4.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type MyInt int
|
||||
|
||||
func Sum[T ~int | float64 | string](a, b T) T {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func main() {
|
||||
var value1, value2 MyInt = 34, 22
|
||||
fmt.Println(Sum(value1, value2)) // 56
|
||||
}
|
||||
17
part_3/3.10/5.go
Normal file
17
part_3/3.10/5.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type MyInt int
|
||||
|
||||
func Sum[T ~int | float64 | string](a, b T) T {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func main() {
|
||||
var value1, value2 MyInt = 34, 22
|
||||
fmt.Println(Sum[MyInt](value1, value2)) // 56
|
||||
fmt.Println(Sum[float64](10.3, 45.1)) // 55.4
|
||||
fmt.Println(Sum[int](10, 45)) // 55
|
||||
fmt.Println(Sum[string]("^_", "^")) // ^_^
|
||||
}
|
||||
21
part_3/3.10/6.go
Normal file
21
part_3/3.10/6.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type MyInt int
|
||||
|
||||
type MyInterface interface {
|
||||
~int | float64 | string | uint16 | uint32
|
||||
}
|
||||
|
||||
func Sum[T MyInterface](a, b T) T {
|
||||
return a + b
|
||||
}
|
||||
|
||||
func main() {
|
||||
var value1, value2 MyInt = 34, 22
|
||||
fmt.Println(Sum(value1, value2)) // 56
|
||||
fmt.Println(Sum(10.3, 45.1)) // 55.4
|
||||
fmt.Println(Sum(10, 45)) // 55
|
||||
fmt.Println(Sum("^_", "^")) // ^_^
|
||||
}
|
||||
28
part_3/3.10/7.go
Normal file
28
part_3/3.10/7.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func reverseSlice[T any](slice []T) []T {
|
||||
length := len(slice)
|
||||
newSlice := make([]T, length)
|
||||
|
||||
for i, elem := range slice {
|
||||
newSlice[length-i-1] = elem
|
||||
}
|
||||
return newSlice
|
||||
}
|
||||
|
||||
func printMySlice[T any](slice []T) {
|
||||
fmt.Printf("Slice values before reverse: %v\n", slice)
|
||||
fmt.Printf("Slice values after reverse: %v\n", reverseSlice(slice))
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func main() {
|
||||
intSlice := []int{1, 3, 4, 6, 7}
|
||||
floatSlice := []float64{3.12, 45.6, 21.6, 5.11}
|
||||
stringSlice := []string{"Oo", "^_^", "-_-"}
|
||||
printMySlice(intSlice)
|
||||
printMySlice(floatSlice)
|
||||
printMySlice(stringSlice)
|
||||
}
|
||||
53
part_3/3.10/8.go
Normal file
53
part_3/3.10/8.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func GetMapValues[K comparable, V any](m map[K]V) []V {
|
||||
// вернет срез из значений словаря
|
||||
values := make([]V, len(m))
|
||||
idx := 0
|
||||
for _, v := range m {
|
||||
values[idx] = v
|
||||
idx++
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func GetMapKeys[K comparable, V any](m map[K]V) []K {
|
||||
// вернет срез из ключей словаря
|
||||
keys := make([]K, len(m))
|
||||
idx := 0
|
||||
for k, _ := range m {
|
||||
keys[idx] = k
|
||||
idx++
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func CreateNewMap[K comparable, V any](k []K, v []V) map[K]V {
|
||||
// создание словаря из двух срезов
|
||||
newMap := make(map[K]V)
|
||||
if len(k) < len(v) {
|
||||
for idx, elem := range k {
|
||||
newMap[elem] = v[idx]
|
||||
}
|
||||
} else {
|
||||
for idx, elem := range v {
|
||||
newMap[k[idx]] = elem
|
||||
}
|
||||
}
|
||||
return newMap
|
||||
}
|
||||
|
||||
func main() {
|
||||
intSlice := []int{1, 3, 4, 6, 7}
|
||||
stringSlice := []string{"Oo", "^_^", "-_-"}
|
||||
myMap := map[int]string{
|
||||
1: "Alex",
|
||||
2: "Maxim",
|
||||
200: "Jon",
|
||||
}
|
||||
fmt.Println(GetMapKeys(myMap)) // [1 2 200]
|
||||
fmt.Println(GetMapValues(myMap)) // [Alex Maxim Jon]
|
||||
fmt.Println(CreateNewMap(intSlice, stringSlice)) // map[1:Oo 3:^_^ 4:-_-]
|
||||
}
|
||||
38
part_3/3.10/9.go
Normal file
38
part_3/3.10/9.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type MyStruct[K string | uint, T string | []string] struct {
|
||||
id K
|
||||
data T
|
||||
}
|
||||
|
||||
func (m *MyStruct[K, T]) getID() K {
|
||||
return m.id
|
||||
}
|
||||
|
||||
func (m *MyStruct[K, T]) getData() T {
|
||||
return m.data
|
||||
}
|
||||
|
||||
func (m *MyStruct[K, T]) setData(data T) {
|
||||
m.data = data
|
||||
}
|
||||
|
||||
func main() {
|
||||
myStruct := MyStruct[uint, string]{
|
||||
id: 1,
|
||||
data: "Oo",
|
||||
}
|
||||
fmt.Printf("K = int, T = string: %+v\n", myStruct)
|
||||
myStruct.setData("^_^")
|
||||
fmt.Printf("K = int, T = string: %+v\n", myStruct)
|
||||
|
||||
newStruct := MyStruct[string, []string]{
|
||||
id: "0xA321",
|
||||
data: []string{"10", "20", "30"},
|
||||
}
|
||||
fmt.Printf("K = string, T = []string: %+v\n", newStruct)
|
||||
newStruct.setData([]string{})
|
||||
fmt.Printf("K = string, T = []string: %+v\n", newStruct)
|
||||
}
|
||||
24
part_3/3.2/1.go
Normal file
24
part_3/3.2/1.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type RUB uint // пользовательский именованный тип RUB
|
||||
|
||||
const RUB2USD uint = 61
|
||||
const RUB2EUR uint = 65
|
||||
|
||||
//связываем тип RUB с методом конвертации рублей в доллары
|
||||
func (r RUB) convertRUB2USD() uint {
|
||||
return uint(r) / RUB2USD
|
||||
}
|
||||
|
||||
//связываем тип RUB с методом конвертации рублей в евро
|
||||
func (r RUB) convertRUB2EUR() uint {
|
||||
return uint(r) / RUB2EUR
|
||||
}
|
||||
|
||||
func main() {
|
||||
var rub RUB = 3475
|
||||
fmt.Printf("%d рублей примерно = %d долларов\n", rub, rub.convertRUB2USD())
|
||||
fmt.Printf("%d рублей примерно = %d евро\n", rub, rub.convertRUB2EUR())
|
||||
}
|
||||
29
part_3/3.2/2.go
Normal file
29
part_3/3.2/2.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type RUB uint // пользовательский именованный тип RUB
|
||||
|
||||
const RUB2USD uint = 61
|
||||
const RUB2EUR uint = 65
|
||||
|
||||
//связываем тип RUB с методом конвертации рублей в доллары
|
||||
func (r RUB) convertRUB2USD() uint {
|
||||
return uint(r) / RUB2USD
|
||||
}
|
||||
|
||||
//связываем тип RUB с методом конвертации рублей в евро
|
||||
func (r RUB) convertRUB2EUR() uint {
|
||||
return uint(r) / RUB2EUR
|
||||
}
|
||||
|
||||
func (r RUB) setNewValue(rub RUB) {
|
||||
r = rub
|
||||
fmt.Printf("В кошельке теперь %d рублей\n", r)
|
||||
}
|
||||
|
||||
func main() {
|
||||
var rub RUB = 3475
|
||||
rub.setNewValue(9000)
|
||||
fmt.Printf("В кошельке на самом деле %d рублей\n", rub)
|
||||
}
|
||||
29
part_3/3.2/3.go
Normal file
29
part_3/3.2/3.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type RUB uint // пользовательский именованный тип RUB
|
||||
|
||||
const RUB2USD uint = 61
|
||||
const RUB2EUR uint = 65
|
||||
|
||||
//связываем тип RUB с методом конвертации рублей в доллары
|
||||
func (r RUB) convertRUB2USD() uint {
|
||||
return uint(r) / RUB2USD
|
||||
}
|
||||
|
||||
//связываем тип RUB с методом конвертации рублей в евро
|
||||
func (r RUB) convertRUB2EUR() uint {
|
||||
return uint(r) / RUB2EUR
|
||||
}
|
||||
|
||||
func (r *RUB) setNewValue(rub RUB) {
|
||||
*r = rub
|
||||
fmt.Printf("В кошельке теперь %d рублей\n", *r)
|
||||
}
|
||||
|
||||
func main() {
|
||||
var rub RUB = 3475
|
||||
rub.setNewValue(9000)
|
||||
fmt.Printf("В кошельке на самом деле %d рублей\n", rub)
|
||||
}
|
||||
3
part_3/3.3/golang/factory/go.mod
Normal file
3
part_3/3.3/golang/factory/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module golang/factory
|
||||
|
||||
go 1.24
|
||||
19
part_3/3.3/golang/factory/main.go
Normal file
19
part_3/3.3/golang/factory/main.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang/factory/shape"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
myShape := shape.Shape{
|
||||
Name: "Cube",
|
||||
Center: shape.Point{X: 4, Y: 5},
|
||||
}
|
||||
|
||||
fmt.Printf("%+v\n", myShape) // {Name:Cube Center:{X:4 Y:5} color:}
|
||||
myShape.SetColor("Gold")
|
||||
fmt.Printf("%+v\n", myShape) // {Name:Cube Center:{X:4 Y:5} color:Gold}
|
||||
fmt.Printf("Shape color: %v\n", myShape.GetColor()) // Shape color: Gold
|
||||
}
|
||||
20
part_3/3.3/golang/factory/shape/shape.go
Normal file
20
part_3/3.3/golang/factory/shape/shape.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package shape
|
||||
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
|
||||
type Shape struct {
|
||||
Name string
|
||||
Center Point
|
||||
color string
|
||||
}
|
||||
|
||||
func (s *Shape) SetColor(color string) {
|
||||
s.color = color
|
||||
}
|
||||
|
||||
func (s *Shape) GetColor() string {
|
||||
return s.color
|
||||
}
|
||||
3
part_3/3.4/golang/factory/go.mod
Normal file
3
part_3/3.4/golang/factory/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module golang/factory
|
||||
|
||||
go 1.24
|
||||
13
part_3/3.4/golang/factory/main.go
Normal file
13
part_3/3.4/golang/factory/main.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang/factory/shape"
|
||||
)
|
||||
|
||||
func main() {
|
||||
myShape1 := shape.NewShape("Cube", "Gold", 4, 5)
|
||||
myShape2 := shape.NewShapeWithPoint("Circle", "Green", shape.Point{X: 5, Y: 7})
|
||||
fmt.Printf("%+v\n", myShape1) // {Name:Cube Center:{X:4 Y:5} color:Gold}
|
||||
fmt.Printf("%+v\n", *myShape2) // {Name:Circle Center:{X:5 Y:7} color:Green}
|
||||
}
|
||||
36
part_3/3.4/golang/factory/shape/shape.go
Normal file
36
part_3/3.4/golang/factory/shape/shape.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package shape
|
||||
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
|
||||
type Shape struct {
|
||||
Name string
|
||||
Center Point
|
||||
color string
|
||||
}
|
||||
|
||||
func (s *Shape) SetColor(color string) {
|
||||
s.color = color
|
||||
}
|
||||
|
||||
func (s *Shape) GetColor() string {
|
||||
return s.color
|
||||
}
|
||||
|
||||
func NewShape(name, color string, x, y int) Shape {
|
||||
return Shape{
|
||||
Name: name,
|
||||
color: color,
|
||||
Center: Point{X: x, Y: y},
|
||||
}
|
||||
}
|
||||
|
||||
func NewShapeWithPoint(name, color string, center Point) *Shape {
|
||||
return &Shape{
|
||||
Name: name,
|
||||
color: color,
|
||||
Center: center,
|
||||
}
|
||||
}
|
||||
3
part_3/3.6/golang/factory/go.mod
Normal file
3
part_3/3.6/golang/factory/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module golang/factory
|
||||
|
||||
go 1.24
|
||||
24
part_3/3.6/golang/factory/main.go
Normal file
24
part_3/3.6/golang/factory/main.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang/factory/shape"
|
||||
)
|
||||
|
||||
func main() {
|
||||
rectangle := shape.NewRectangle(10, 6, shape.Point{X: 6, Y: -8}, "Gold")
|
||||
|
||||
fmt.Printf("%+v\n", *rectangle)
|
||||
fmt.Printf("%+v\n", rectangle.GetName())
|
||||
fmt.Printf("Perimeter = %+v\n", rectangle.GetPerimeter())
|
||||
fmt.Printf("Area = %+v\n", rectangle.GetArea())
|
||||
|
||||
// меняем значения полей
|
||||
rectangle.SetLength(15)
|
||||
rectangle.SetWidth(7)
|
||||
rectangle.SetColor("Green")
|
||||
|
||||
fmt.Printf("%+v\n", *rectangle)
|
||||
fmt.Printf("New perimeter = %+v\n", rectangle.GetPerimeter())
|
||||
fmt.Printf("New Area = %+v\n", rectangle.GetArea())
|
||||
}
|
||||
47
part_3/3.6/golang/factory/shape/rectangle.go
Normal file
47
part_3/3.6/golang/factory/shape/rectangle.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package shape
|
||||
|
||||
type Rectangle struct {
|
||||
shape // композиция
|
||||
width uint
|
||||
length uint
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetWidth() uint {
|
||||
return r.width
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetLength() uint {
|
||||
return r.length
|
||||
}
|
||||
|
||||
func (r *Rectangle) SetWidth(width uint) {
|
||||
r.width = width
|
||||
}
|
||||
|
||||
func (r *Rectangle) SetLength(length uint) {
|
||||
r.length = length
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetPerimeter() uint {
|
||||
return (r.length + r.width) * 2
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetArea() uint {
|
||||
return r.length * r.width
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetName() string {
|
||||
return "Super-puper " + r.shape.GetName()
|
||||
}
|
||||
|
||||
func NewRectangle(width, length uint, center Point, color string) *Rectangle {
|
||||
return &Rectangle{
|
||||
shape: shape{
|
||||
name: "Rectangle",
|
||||
color: color,
|
||||
center: center,
|
||||
},
|
||||
width: width,
|
||||
length: length,
|
||||
}
|
||||
}
|
||||
32
part_3/3.6/golang/factory/shape/shape.go
Normal file
32
part_3/3.6/golang/factory/shape/shape.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package shape
|
||||
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
|
||||
type shape struct {
|
||||
name string
|
||||
center Point
|
||||
color string
|
||||
}
|
||||
|
||||
func (s *shape) SetColor(color string) {
|
||||
s.color = color
|
||||
}
|
||||
|
||||
func (s *shape) GetColor() string {
|
||||
return s.color
|
||||
}
|
||||
|
||||
func (s *shape) GetName() string {
|
||||
return s.name
|
||||
}
|
||||
|
||||
func (s *shape) MoveCenter(point Point) {
|
||||
s.center = point
|
||||
}
|
||||
|
||||
func (s *shape) GetCenter() Point {
|
||||
return s.center
|
||||
}
|
||||
3
part_3/3.7/golang/factory/go.mod
Normal file
3
part_3/3.7/golang/factory/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module golang/factory
|
||||
|
||||
go 1.24
|
||||
85
part_3/3.7/golang/factory/main.go
Normal file
85
part_3/3.7/golang/factory/main.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang/factory/shape"
|
||||
)
|
||||
|
||||
func printShapeName(name shape.IShapeName) {
|
||||
fmt.Printf("IShapeName: %v\n", name.GetName())
|
||||
}
|
||||
|
||||
func getIShapeFromRectangle(rectangle *shape.Rectangle) shape.IShape {
|
||||
return rectangle // неявное приведение
|
||||
// return shape.IShape(rectangle) // явное приведение
|
||||
}
|
||||
|
||||
func main() {
|
||||
rectangle := shape.NewRectangle(10, 6, shape.Point{X: 6, Y: -8}, "Gold")
|
||||
|
||||
ishape := shape.IShape(rectangle) // приведение Rectangle к интерфейсу
|
||||
// приведение интерфейса IShape к интерфейсу IShapeArea
|
||||
iShapeArea := shape.IShapeArea(ishape)
|
||||
fmt.Printf("IShapeArea: %+v\n", iShapeArea.GetArea())
|
||||
|
||||
// явное обратное приведение интерфейса IShapePerimeter к интерфейсу IShape невозможно
|
||||
// ishape = shape.IShape(iShapePerimeter) //error:
|
||||
// cannot convert iShapePerimeter (variable of type shape.IShapePerimeter) to shape.IShape
|
||||
// (shape.IShapePerimeter does not implement shape.IShape (missing method GetArea))
|
||||
|
||||
// правильное приведение интерфейса IShapeArea к интерфейсу IShape
|
||||
ishape = iShapeArea.(*shape.Rectangle)
|
||||
// аналогично
|
||||
// newIshape := shape.IShape(iShapeArea.(*shape.Rectangle))
|
||||
fmt.Printf("IShape center: %+v\n", ishape.GetCenter())
|
||||
|
||||
// правильное приведение интерфейса IShapeArea к структуре Rectangle
|
||||
rectangle = iShapeArea.(*shape.Rectangle)
|
||||
fmt.Printf("%s: %+v\n", rectangle.GetName(), *rectangle)
|
||||
}
|
||||
|
||||
// func main() {
|
||||
// rectangle1 := shape.NewRectangle(10, 6, shape.Point{X: 6, Y: -8}, "Gold")
|
||||
// triangle1 := shape.NewTriangle(6, 10, 8, shape.Point{X: -85, Y: 15}, "Green")
|
||||
// rectangle2 := shape.NewRectangle(3, 5, shape.Point{X: 46, Y: -48}, "Yellow")
|
||||
// triangle2 := shape.NewTriangle(4, 8, 6, shape.Point{X: 61, Y: 98}, "Orange")
|
||||
|
||||
// // объявляем и инициализируем срез интерфейсного типа
|
||||
// ishapeSlice := []shape.IShape{
|
||||
// rectangle1,
|
||||
// triangle1,
|
||||
// triangle2,
|
||||
// rectangle2,
|
||||
// }
|
||||
|
||||
// for _, it := range ishapeSlice {
|
||||
// fmt.Printf("Shape center coordinate: %+v\n", it.GetCenter())
|
||||
// newCenter := shape.Point{
|
||||
// X: it.GetCenter().X + 33,
|
||||
// Y: it.GetCenter().Y - 20,
|
||||
// }
|
||||
// it.MoveCenter(newCenter)
|
||||
// fmt.Printf("Shape new center coordinate: %+v\n", it.GetCenter())
|
||||
// fmt.Println()
|
||||
// }
|
||||
// }
|
||||
|
||||
// func main() {
|
||||
// rectangle := shape.NewRectangle(10, 6, shape.Point{X: 6, Y: -8}, "Gold")
|
||||
// triangle := shape.NewTriangle(6, 10, 8, shape.Point{X: -85, Y: 15}, "Green")
|
||||
// printShapeName(rectangle) // неявное приведение
|
||||
// //printShapeName(shape.IShapeName(rectangle)) // явное приведение
|
||||
// printShapeName(triangle)
|
||||
// ishape := getIShapeFromRectangle(rectangle)
|
||||
// fmt.Printf("Shape center: %v\n", ishape.GetCenter())
|
||||
// fmt.Printf("Shape perimeter: %v\n", ishape.GetPerimeter())
|
||||
// }
|
||||
|
||||
// func main() {
|
||||
// rectangle := shape.NewRectangle(10, 6, shape.Point{X: 6, Y: -8}, "Gold")
|
||||
// triangle := shape.NewTriangle(6, 10, 8, shape.Point{X: -85, Y: 15}, "Green")
|
||||
// iShapeName := shape.IShapeName(triangle) // приведение Triangle к интерфейсу
|
||||
// fmt.Printf("IShapeName: %v\n", iShapeName.GetName())
|
||||
// iShapeName = shape.IShapeName(rectangle) // приведение Rectangle к интерфейсу
|
||||
// fmt.Printf("IShapeName: %v\n", iShapeName.GetName())
|
||||
// }
|
||||
20
part_3/3.7/golang/factory/shape/ishape.go
Normal file
20
part_3/3.7/golang/factory/shape/ishape.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package shape
|
||||
|
||||
type IShape interface {
|
||||
GetArea() float64
|
||||
GetPerimeter() uint
|
||||
MoveCenter(point Point)
|
||||
GetCenter() Point
|
||||
}
|
||||
|
||||
type IShapeArea interface {
|
||||
GetArea() float64
|
||||
}
|
||||
|
||||
type IShapePerimeter interface {
|
||||
GetPerimeter() uint
|
||||
}
|
||||
|
||||
type IShapeName interface {
|
||||
GetName() string
|
||||
}
|
||||
47
part_3/3.7/golang/factory/shape/rectangle.go
Normal file
47
part_3/3.7/golang/factory/shape/rectangle.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package shape
|
||||
|
||||
type Rectangle struct {
|
||||
shape // композиция
|
||||
width uint
|
||||
length uint
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetWidth() uint {
|
||||
return r.width
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetLength() uint {
|
||||
return r.length
|
||||
}
|
||||
|
||||
func (r *Rectangle) SetWidth(width uint) {
|
||||
r.width = width
|
||||
}
|
||||
|
||||
func (r *Rectangle) SetLength(length uint) {
|
||||
r.length = length
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetPerimeter() uint {
|
||||
return (r.length + r.width) * 2
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetArea() float64 {
|
||||
return float64(r.length * r.width)
|
||||
}
|
||||
|
||||
func (r *Rectangle) GetName() string {
|
||||
return "Super-puper " + r.shape.GetName()
|
||||
}
|
||||
|
||||
func NewRectangle(width, length uint, center Point, color string) *Rectangle {
|
||||
return &Rectangle{
|
||||
shape: shape{
|
||||
name: "Rectangle",
|
||||
color: color,
|
||||
center: center,
|
||||
},
|
||||
width: width,
|
||||
length: length,
|
||||
}
|
||||
}
|
||||
32
part_3/3.7/golang/factory/shape/shape.go
Normal file
32
part_3/3.7/golang/factory/shape/shape.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package shape
|
||||
|
||||
type Point struct {
|
||||
X int
|
||||
Y int
|
||||
}
|
||||
|
||||
type shape struct {
|
||||
name string
|
||||
center Point
|
||||
color string
|
||||
}
|
||||
|
||||
func (s *shape) SetColor(color string) {
|
||||
s.color = color
|
||||
}
|
||||
|
||||
func (s *shape) GetColor() string {
|
||||
return s.color
|
||||
}
|
||||
|
||||
func (s *shape) GetName() string {
|
||||
return s.name
|
||||
}
|
||||
|
||||
func (s *shape) MoveCenter(point Point) {
|
||||
s.center = point
|
||||
}
|
||||
|
||||
func (s *shape) GetCenter() Point {
|
||||
return s.center
|
||||
}
|
||||
64
part_3/3.7/golang/factory/shape/triangle.go
Normal file
64
part_3/3.7/golang/factory/shape/triangle.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package shape
|
||||
|
||||
import "math"
|
||||
|
||||
type Triangle struct {
|
||||
shape
|
||||
abLength uint
|
||||
acLength uint
|
||||
bcLength uint
|
||||
}
|
||||
|
||||
func (t *Triangle) GetABLength() uint {
|
||||
return t.abLength
|
||||
}
|
||||
|
||||
func (t *Triangle) GetACLength() uint {
|
||||
return t.acLength
|
||||
}
|
||||
|
||||
func (t *Triangle) GetBCLength() uint {
|
||||
return t.bcLength
|
||||
}
|
||||
|
||||
func (t *Triangle) SetABLength(ab uint) {
|
||||
t.abLength = ab
|
||||
}
|
||||
|
||||
func (t *Triangle) SetACLength(ac uint) {
|
||||
t.abLength = ac
|
||||
}
|
||||
|
||||
func (t *Triangle) SetBCLength(bc uint) {
|
||||
t.abLength = bc
|
||||
}
|
||||
|
||||
func (t *Triangle) GetPerimeter() uint {
|
||||
return t.abLength + t.acLength + t.bcLength
|
||||
}
|
||||
|
||||
func (t *Triangle) GetArea() float64 {
|
||||
// расчет площади треугольника
|
||||
// высота рассчитывается по формуле разностороннего треугольника
|
||||
// через длины всех сторон
|
||||
p := float64(t.GetPerimeter() / 2) // полупериметр
|
||||
numerator := p * (p - float64(t.abLength)) *
|
||||
(p - float64(t.acLength)) *
|
||||
(p - float64(t.acLength))
|
||||
numerator = 2 * math.Sqrt(numerator)
|
||||
height := numerator / 2
|
||||
return float64(t.acLength) / 2 * height
|
||||
}
|
||||
|
||||
func NewTriangle(ab, ac, bc uint, center Point, color string) *Triangle {
|
||||
return &Triangle{
|
||||
shape: shape{
|
||||
name: "Triangle",
|
||||
color: color,
|
||||
center: center,
|
||||
},
|
||||
abLength: ab,
|
||||
bcLength: bc,
|
||||
acLength: ac,
|
||||
}
|
||||
}
|
||||
3
part_3/3.8/golang/car_factory/go.mod
Normal file
3
part_3/3.8/golang/car_factory/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module golang/car_factory
|
||||
|
||||
go 1.24
|
||||
35
part_3/3.8/golang/car_factory/main.go
Normal file
35
part_3/3.8/golang/car_factory/main.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang/car_factory/vehicle"
|
||||
"golang/car_factory/vehicle/motor"
|
||||
)
|
||||
|
||||
func printCarInfo(car *vehicle.Car) {
|
||||
fmt.Printf("----------- %v -----------\n", car.GetBrand())
|
||||
fmt.Printf("Car: %+v\n", car)
|
||||
fmt.Printf("motor: %+v\n", car.GetMotorData())
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func main() {
|
||||
car := vehicle.NewDefaultCar()
|
||||
printCarInfo(car)
|
||||
car.StartMove()
|
||||
car.StartMotor()
|
||||
car.StartMove()
|
||||
car.StoptMotor()
|
||||
fmt.Println("Is car move? ", car.IsMove())
|
||||
|
||||
// меняем двигатель
|
||||
newMotor := motor.NewHyundaiMotor("1.8")
|
||||
car.ChangeMotor(newMotor)
|
||||
|
||||
printCarInfo(car)
|
||||
printCarInfo(car)
|
||||
car.StartMove()
|
||||
car.StartMotor()
|
||||
car.StartMove()
|
||||
fmt.Println("Is car move? ", car.IsMove())
|
||||
}
|
||||
87
part_3/3.8/golang/car_factory/vehicle/car.go
Normal file
87
part_3/3.8/golang/car_factory/vehicle/car.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package vehicle
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang/car_factory/vehicle/motor"
|
||||
)
|
||||
|
||||
type Car struct {
|
||||
motor motor.IMotor
|
||||
isLeftHandDrive bool
|
||||
brand string
|
||||
isMove bool
|
||||
}
|
||||
|
||||
func (c *Car) GetBrand() string {
|
||||
return c.brand
|
||||
}
|
||||
|
||||
func (c *Car) ChangeMotor(motor motor.IMotor) {
|
||||
fmt.Println()
|
||||
fmt.Println("-------- Change Motor --------")
|
||||
fmt.Printf("Old motor: %+v\n", c.motor)
|
||||
c.motor = motor
|
||||
fmt.Printf("New motor: %+v\n", c.motor)
|
||||
fmt.Println()
|
||||
}
|
||||
|
||||
func (c *Car) IsLeftHandDrive() bool {
|
||||
return c.isLeftHandDrive
|
||||
}
|
||||
|
||||
func (c *Car) StartMotor() {
|
||||
c.motor.RunMotor()
|
||||
}
|
||||
|
||||
func (c *Car) StoptMotor() {
|
||||
c.motor.StopMotor()
|
||||
c.isMove = false
|
||||
}
|
||||
|
||||
func (c *Car) StartMove() {
|
||||
if c.motor.IsRun() {
|
||||
c.isMove = true
|
||||
fmt.Printf("Сar '%v' started moving\n", c.brand)
|
||||
} else {
|
||||
fmt.Printf("Сar '%v' can't start moving\n", c.brand)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Car) StopMove() {
|
||||
if c.isMove {
|
||||
c.isMove = false
|
||||
fmt.Printf("Сar '%v' stopped \n", c.brand)
|
||||
} else {
|
||||
fmt.Println("To stop first start moving")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Car) GetMotorData() string {
|
||||
return fmt.Sprintf("%+v", c.motor)
|
||||
}
|
||||
|
||||
func (c *Car) GetMotorPower() string {
|
||||
return c.motor.GetPower()
|
||||
}
|
||||
|
||||
func (c *Car) IsMove() bool {
|
||||
return c.isMove
|
||||
}
|
||||
|
||||
func NewCar(brand string, motor motor.IMotor, isLeftHandDrive bool) *Car {
|
||||
return &Car{
|
||||
motor: motor,
|
||||
brand: brand,
|
||||
isLeftHandDrive: isLeftHandDrive,
|
||||
isMove: false,
|
||||
}
|
||||
}
|
||||
|
||||
func NewDefaultCar() *Car {
|
||||
return &Car{
|
||||
motor: motor.NewAutoVazMotor("1.6"),
|
||||
brand: "Lada",
|
||||
isLeftHandDrive: false,
|
||||
isMove: false,
|
||||
}
|
||||
}
|
||||
23
part_3/3.8/golang/car_factory/vehicle/motor/avtovaz_motor.go
Normal file
23
part_3/3.8/golang/car_factory/vehicle/motor/avtovaz_motor.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package motor
|
||||
|
||||
type AvtoVazMotor struct {
|
||||
Motor
|
||||
}
|
||||
|
||||
func NewAutoVazMotor(power string) *AvtoVazMotor {
|
||||
motor := &AvtoVazMotor{
|
||||
Motor: Motor{
|
||||
manufacturer: autoVAZ,
|
||||
isRun: false,
|
||||
},
|
||||
}
|
||||
switch power {
|
||||
case "1.6":
|
||||
motor.amountСylinders = 4
|
||||
motor.power = power
|
||||
default:
|
||||
motor.amountСylinders = 4
|
||||
motor.power = defaultPower
|
||||
}
|
||||
return motor
|
||||
}
|
||||
40
part_3/3.8/golang/car_factory/vehicle/motor/hyundai_motor.go
Normal file
40
part_3/3.8/golang/car_factory/vehicle/motor/hyundai_motor.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package motor
|
||||
|
||||
type HyundaiMotor struct {
|
||||
Motor
|
||||
turboMod bool
|
||||
}
|
||||
|
||||
func (m *HyundaiMotor) IsTurboModOn() bool {
|
||||
return m.turboMod
|
||||
}
|
||||
|
||||
func (m *HyundaiMotor) TurboModOn() {
|
||||
m.turboMod = true
|
||||
}
|
||||
|
||||
func (m *HyundaiMotor) TurboModoff() {
|
||||
m.turboMod = false
|
||||
}
|
||||
|
||||
func NewHyundaiMotor(power string) *HyundaiMotor {
|
||||
motor := &HyundaiMotor{
|
||||
Motor: Motor{
|
||||
manufacturer: hyundai,
|
||||
isRun: false,
|
||||
},
|
||||
turboMod: false,
|
||||
}
|
||||
switch power {
|
||||
case "1.8":
|
||||
motor.amountСylinders = 6
|
||||
motor.power = power
|
||||
case "1.6":
|
||||
motor.amountСylinders = 4
|
||||
motor.power = power
|
||||
default:
|
||||
motor.amountСylinders = 4
|
||||
motor.power = defaultPower
|
||||
}
|
||||
return motor
|
||||
}
|
||||
10
part_3/3.8/golang/car_factory/vehicle/motor/imotor.go
Normal file
10
part_3/3.8/golang/car_factory/vehicle/motor/imotor.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package motor
|
||||
|
||||
type IMotor interface {
|
||||
GetPower() string
|
||||
RunMotor()
|
||||
StopMotor()
|
||||
IsRun() bool
|
||||
AmountСylinders() uint8
|
||||
GetManufacturerName() string
|
||||
}
|
||||
40
part_3/3.8/golang/car_factory/vehicle/motor/motor.go
Normal file
40
part_3/3.8/golang/car_factory/vehicle/motor/motor.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package motor
|
||||
|
||||
import "fmt"
|
||||
|
||||
const hyundai = "Hyundai"
|
||||
const autoVAZ = "Автоваз"
|
||||
const defaultPower = "1.4"
|
||||
|
||||
type Motor struct {
|
||||
power string
|
||||
amountСylinders uint8
|
||||
isRun bool
|
||||
manufacturer string
|
||||
}
|
||||
|
||||
func (m *Motor) GetPower() string {
|
||||
return m.power
|
||||
}
|
||||
|
||||
func (m *Motor) RunMotor() {
|
||||
fmt.Println("Motor is run")
|
||||
m.isRun = true
|
||||
}
|
||||
|
||||
func (m *Motor) StopMotor() {
|
||||
fmt.Println("Motor is stop")
|
||||
m.isRun = false
|
||||
}
|
||||
|
||||
func (m *Motor) IsRun() bool {
|
||||
return m.isRun
|
||||
}
|
||||
|
||||
func (m *Motor) AmountСylinders() uint8 {
|
||||
return m.amountСylinders
|
||||
}
|
||||
|
||||
func (m *Motor) GetManufacturerName() string {
|
||||
return m.manufacturer
|
||||
}
|
||||
8
part_3/3.9/1.go
Normal file
8
part_3/3.9/1.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
var myInterface interface{}
|
||||
fmt.Printf("%v", myInterface) // <nil>
|
||||
}
|
||||
19
part_3/3.9/2.go
Normal file
19
part_3/3.9/2.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type shape struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (s *shape) getName() string {
|
||||
return s.name
|
||||
}
|
||||
|
||||
func main() {
|
||||
var firstInterface interface{} = shape{name: "Cube"}
|
||||
var secondInterface interface{} = "Oo"
|
||||
|
||||
fmt.Printf("%+v\n", firstInterface) // {name:Cube}
|
||||
fmt.Printf("%+v\n", secondInterface) // Oo
|
||||
}
|
||||
20
part_3/3.9/3.go
Normal file
20
part_3/3.9/3.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type shape struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (s *shape) getName() string {
|
||||
return s.name
|
||||
}
|
||||
|
||||
func main() {
|
||||
var firstInterface interface{} = shape{name: "Cube"}
|
||||
var secondInterface interface{} = "Oo"
|
||||
|
||||
fmt.Printf("%+v\n", secondInterface.(string)) // ok
|
||||
fmt.Printf("%+v\n", firstInterface.(string)) // error
|
||||
|
||||
}
|
||||
30
part_3/3.9/4.go
Normal file
30
part_3/3.9/4.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type shape struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (s *shape) getName() string {
|
||||
return s.name
|
||||
}
|
||||
|
||||
func main() {
|
||||
var firstInterface interface{} = shape{name: "Cube"}
|
||||
value, ok := firstInterface.(string)
|
||||
|
||||
if ok {
|
||||
fmt.Println(value) // работаем со значением
|
||||
} else {
|
||||
fmt.Println("Wrong type assertion!")
|
||||
}
|
||||
|
||||
newValue, newOk := firstInterface.(shape)
|
||||
|
||||
if newOk {
|
||||
fmt.Println(newValue.getName())
|
||||
} else {
|
||||
fmt.Println("Wrong type assertion!")
|
||||
}
|
||||
}
|
||||
23
part_3/3.9/5.go
Normal file
23
part_3/3.9/5.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type shape struct{}
|
||||
type car struct{}
|
||||
|
||||
func checkType(i interface{}) {
|
||||
switch i.(type) {
|
||||
case shape:
|
||||
fmt.Println("It is shape")
|
||||
case car:
|
||||
fmt.Println("It is car")
|
||||
default:
|
||||
fmt.Println("What is this pokemon?")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
checkType(shape{})
|
||||
checkType(car{})
|
||||
checkType(6)
|
||||
}
|
||||
24
part_3/3.9/6.go
Normal file
24
part_3/3.9/6.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type shape struct{}
|
||||
type car struct{}
|
||||
|
||||
func isEqual(i interface{}, j interface{}) {
|
||||
if i == j { // одинаковое значение и базовый тип?
|
||||
fmt.Println("Equal")
|
||||
} else {
|
||||
fmt.Println("Inequal")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
isEqual(shape{}, shape{}) // Equal
|
||||
isEqual(shape{}, car{}) // Inequal
|
||||
|
||||
var firstInterface interface{} // по умолчанию - nil
|
||||
var secondInterface interface{}
|
||||
|
||||
isEqual(firstInterface, secondInterface) // Equal
|
||||
}
|
||||
14
part_3/tic_tac_toe/.vscode/launch.json
vendored
Normal file
14
part_3/tic_tac_toe/.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
{
|
||||
"name": "Launch Package",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${fileDirname}", // <- ставим запятую
|
||||
"console": "integratedTerminal"
|
||||
}
|
||||
]
|
||||
}
|
||||
113
part_3/tic_tac_toe/game/board.go
Normal file
113
part_3/tic_tac_toe/game/board.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const (
|
||||
BoardDefaultSize int = 3
|
||||
BoardMinSize int = 3
|
||||
BoardMaxSize int = 9
|
||||
)
|
||||
|
||||
type Board struct {
|
||||
board [][]BoardField
|
||||
size int
|
||||
}
|
||||
|
||||
func NewBoard(size int) *Board {
|
||||
board := make([][]BoardField, size)
|
||||
for i := range board {
|
||||
board[i] = make([]BoardField, size)
|
||||
}
|
||||
return &Board{board: board, size: size}
|
||||
}
|
||||
|
||||
// Отображение игрового поля
|
||||
func (b *Board) printBoard() {
|
||||
fmt.Print(" ")
|
||||
for i := range b.size {
|
||||
fmt.Printf("%d ", i+1)
|
||||
}
|
||||
fmt.Println()
|
||||
for i := range b.size {
|
||||
fmt.Printf("%d ", i+1)
|
||||
for j := range b.size {
|
||||
switch b.board[i][j] {
|
||||
case empty:
|
||||
fmt.Print(". ")
|
||||
case cross:
|
||||
fmt.Print("X ")
|
||||
case nought:
|
||||
fmt.Print("O ")
|
||||
}
|
||||
}
|
||||
fmt.Println()
|
||||
}
|
||||
}
|
||||
|
||||
// Проверка возможности и выполнения хода
|
||||
func (b *Board) makeMove(x, y int) bool {
|
||||
return b.board[x][y] == empty
|
||||
}
|
||||
|
||||
func (b *Board) setSymbol(x, y int, player BoardField) bool {
|
||||
if b.makeMove(x, y) {
|
||||
b.board[x][y] = player
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Проверка выигрыша
|
||||
func (b *Board) checkWin(player BoardField) bool {
|
||||
// Проверка строк и столбцов
|
||||
for i := range b.size {
|
||||
rowWin, colWin := true, true
|
||||
for j := range b.size {
|
||||
if b.board[i][j] != player {
|
||||
rowWin = false
|
||||
}
|
||||
if b.board[j][i] != player {
|
||||
colWin = false
|
||||
}
|
||||
}
|
||||
if rowWin || colWin {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Главная диагональ
|
||||
mainDiag := true
|
||||
for i := range b.size {
|
||||
if b.board[i][i] != player {
|
||||
mainDiag = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if mainDiag {
|
||||
return true
|
||||
}
|
||||
|
||||
// Побочная диагональ
|
||||
antiDiag := true
|
||||
for i := range b.size {
|
||||
if b.board[i][b.size-i-1] != player {
|
||||
antiDiag = false
|
||||
break
|
||||
}
|
||||
}
|
||||
return antiDiag
|
||||
}
|
||||
|
||||
// Проверка на ничью
|
||||
func (b *Board) checkDraw() bool {
|
||||
for i := range b.size {
|
||||
for j := range b.size {
|
||||
if b.board[i][j] == empty {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
10
part_3/tic_tac_toe/game/board_cell_type.go
Normal file
10
part_3/tic_tac_toe/game/board_cell_type.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package game
|
||||
|
||||
type BoardField int
|
||||
|
||||
// фигуры в клетке поля
|
||||
const (
|
||||
empty BoardField = iota
|
||||
cross
|
||||
nought
|
||||
)
|
||||
92
part_3/tic_tac_toe/game/game.go
Normal file
92
part_3/tic_tac_toe/game/game.go
Normal file
@@ -0,0 +1,92 @@
|
||||
package game
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Game struct {
|
||||
board *Board
|
||||
player *Player
|
||||
reader *bufio.Reader
|
||||
state GameState
|
||||
}
|
||||
|
||||
func NewGame(board Board, player Player, reader *bufio.Reader) *Game {
|
||||
return &Game{
|
||||
board: &board,
|
||||
player: &player,
|
||||
reader: reader,
|
||||
state: playing,
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Game) updateState() {
|
||||
if g.board.checkWin(g.player.figure) {
|
||||
if g.player.figure == cross {
|
||||
g.state = crossWin
|
||||
} else {
|
||||
g.state = noughtWin
|
||||
}
|
||||
} else if g.board.checkDraw() {
|
||||
g.state = draw
|
||||
}
|
||||
}
|
||||
|
||||
// Игровой цикл
|
||||
func (g *Game) Play() {
|
||||
for g.state == playing {
|
||||
g.board.printBoard()
|
||||
fmt.Printf(
|
||||
"%s's turn. Enter row and column (e.g. 1 2): ",
|
||||
g.player.getSymbol())
|
||||
|
||||
input, err := g.reader.ReadString('\n')
|
||||
if err != nil {
|
||||
fmt.Println("Invalid input. Please try again.")
|
||||
continue
|
||||
}
|
||||
|
||||
input = strings.TrimSpace(input)
|
||||
if input == "q" {
|
||||
g.state = quit
|
||||
break
|
||||
}
|
||||
|
||||
parts := strings.Fields(input)
|
||||
if len(parts) != 2 {
|
||||
fmt.Println("Invalid input. Please try again.")
|
||||
continue
|
||||
}
|
||||
|
||||
row, err1 := strconv.Atoi(parts[0])
|
||||
col, err2 := strconv.Atoi(parts[1])
|
||||
if err1 != nil || err2 != nil ||
|
||||
row < 1 || col < 1 || row > g.board.size ||
|
||||
col > g.board.size {
|
||||
fmt.Println("Invalid input. Please try again.")
|
||||
continue
|
||||
}
|
||||
if g.board.setSymbol(row-1, col-1, g.player.figure) {
|
||||
g.updateState()
|
||||
g.player.switchPlayer()
|
||||
|
||||
} else {
|
||||
fmt.Println("This cell is already occupied!")
|
||||
}
|
||||
}
|
||||
|
||||
g.board.printBoard()
|
||||
|
||||
if g.state == crossWin {
|
||||
fmt.Println("X wins!")
|
||||
} else if g.state == noughtWin {
|
||||
fmt.Println("O wins!")
|
||||
} else if g.state == draw {
|
||||
fmt.Println("It's a draw!")
|
||||
} else {
|
||||
fmt.Println("Game over!")
|
||||
}
|
||||
}
|
||||
12
part_3/tic_tac_toe/game/game_state.go
Normal file
12
part_3/tic_tac_toe/game/game_state.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package game
|
||||
|
||||
type GameState int
|
||||
|
||||
// состояние игрового процесса
|
||||
const (
|
||||
playing GameState = iota
|
||||
draw
|
||||
crossWin
|
||||
noughtWin
|
||||
quit
|
||||
)
|
||||
24
part_3/tic_tac_toe/game/player.go
Normal file
24
part_3/tic_tac_toe/game/player.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package game
|
||||
|
||||
type Player struct {
|
||||
figure BoardField
|
||||
}
|
||||
|
||||
func NewPlayer() *Player {
|
||||
return &Player{figure: cross}
|
||||
}
|
||||
|
||||
func (p *Player) switchPlayer() {
|
||||
if p.figure == cross {
|
||||
p.figure = nought
|
||||
} else {
|
||||
p.figure = cross
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Player) getSymbol() string {
|
||||
if p.figure == cross {
|
||||
return "X"
|
||||
}
|
||||
return "O"
|
||||
}
|
||||
3
part_3/tic_tac_toe/go.mod
Normal file
3
part_3/tic_tac_toe/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module tic-tac-toe
|
||||
|
||||
go 1.24.0
|
||||
40
part_3/tic_tac_toe/main.go
Normal file
40
part_3/tic_tac_toe/main.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"tic-tac-toe/game"
|
||||
)
|
||||
|
||||
func main() {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
boardSize := 0
|
||||
for {
|
||||
fmt.Print("Enter the size of the board (3-9): ")
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
fmt.Println("Error reading input.")
|
||||
continue
|
||||
}
|
||||
input = strings.TrimSpace(input)
|
||||
boardSize, err = strconv.Atoi(input)
|
||||
if err != nil {
|
||||
// Использовать предыдущий размер по умолчанию
|
||||
boardSize = game.BoardDefaultSize
|
||||
}
|
||||
if boardSize < game.BoardMinSize ||
|
||||
boardSize > game.BoardMaxSize {
|
||||
fmt.Println("Invalid board size.")
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
board := game.NewBoard(boardSize)
|
||||
player := game.NewPlayer()
|
||||
game := game.NewGame(*board, *player, reader)
|
||||
game.Play()
|
||||
}
|
||||
Reference in New Issue
Block a user