Compare commits
6 Commits
61976c9a29
...
0.01
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f1afec1ad | ||
|
|
3dc8259d50 | ||
|
|
ecc1e28f0a | ||
|
|
36a52e353d | ||
|
|
b415ca6abf | ||
|
|
2e7b8722ca |
BIN
chapter1/hello
Executable file
BIN
chapter1/hello
Executable file
Binary file not shown.
7
chapter1/hello.go
Normal file
7
chapter1/hello.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("Hello, Go!")
|
||||
}
|
||||
53
chapter2/guess/guess.go
Normal file
53
chapter2/guess/guess.go
Normal file
@@ -0,0 +1,53 @@
|
||||
// guess - игра про отгадывание числа
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
// "time"
|
||||
"bufio"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
/* seconds := time.Now().Unix()
|
||||
rand.Seed(seconds) */ // is deprecated
|
||||
target := rand.Intn(100) + 1
|
||||
fmt.Println("Я загадал число от 1 до 100. Отгадай его: ")
|
||||
// fmt.Println(target)
|
||||
|
||||
reader := bufio.NewReader(os.Stdin) // новый буфер для чтения с клавы
|
||||
|
||||
success := false
|
||||
for guesses := 0; guesses < 10; guesses++ {
|
||||
fmt.Println("У вас есть", 10-guesses, "попыток.")
|
||||
|
||||
fmt.Print("Введите свое число: ")
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
input = strings.TrimSpace(input) // удаление новой строки
|
||||
guess, err := strconv.Atoi(input) // конвертация в int
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
if guess < target {
|
||||
fmt.Println("Ваше число меньше загаданного")
|
||||
} else if guess > target {
|
||||
fmt.Println("Ваше число больше загаданного")
|
||||
} else if guess == target {
|
||||
success = true
|
||||
fmt.Println("Вы угадали число!!!")
|
||||
break
|
||||
}
|
||||
}
|
||||
if !success {
|
||||
fmt.Println("Вы проиграли! Загаданное число", target)
|
||||
}
|
||||
}
|
||||
33
chapter2/pass_fail/pass_fail.go
Normal file
33
chapter2/pass_fail/pass_fail.go
Normal file
@@ -0,0 +1,33 @@
|
||||
// pass_fail сообщает сдал ли пользователь экзамен
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Print("Enter a grade: ")
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
input = strings.TrimSpace(input)
|
||||
grade, err := strconv.ParseFloat(input, 64)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var status string
|
||||
if grade >= 60 {
|
||||
status = "passing"
|
||||
} else if grade < 60 {
|
||||
status = "failing"
|
||||
}
|
||||
fmt.Println("A grade of", grade, "is", status)
|
||||
}
|
||||
13
chapter2/strings/strings.go
Normal file
13
chapter2/strings/strings.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
broken := "G# r#cks!"
|
||||
replacer := strings.NewReplacer("#", "o")
|
||||
fixed := replacer.Replace(broken)
|
||||
fmt.Println(fixed)
|
||||
}
|
||||
13
chapter2/time.go
Normal file
13
chapter2/time.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var now time.Time = time.Now()
|
||||
var year int = now.Year()
|
||||
fmt.Println(year)
|
||||
fmt.Println(now)
|
||||
}
|
||||
30
chapter3/format/format.go
Normal file
30
chapter3/format/format.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
// функция Printf выводит форматированную строку
|
||||
fmt.Printf("About one third %0.2f\n", 1.0/3.0)
|
||||
|
||||
// Функция Sprintf возвращает форматированную строку
|
||||
resultString := fmt.Sprintf("About one third %0.2f\n", 1.0/3.0)
|
||||
fmt.Printf(resultString)
|
||||
|
||||
// Формат %v не выводит спецсимволы
|
||||
fmt.Printf("%v %v %v", "", "\n", "\t")
|
||||
// Формат %#v выводит спецсимволы
|
||||
fmt.Printf("%#v %#v %#v", "", "\n", "\t")
|
||||
fmt.Println("")
|
||||
|
||||
// Форматирование в виде таблицы
|
||||
fmt.Printf("%12s | %s\n", "Product", "Cost in Cents")
|
||||
fmt.Println("-------------+-------------------")
|
||||
fmt.Printf("%12s | %2d\n", "Stamps", 50)
|
||||
fmt.Printf("%12s | %2d\n", "Paper CLips", 5)
|
||||
fmt.Printf("%12s | %2d\n", "Tape", 99)
|
||||
|
||||
fmt.Println("")
|
||||
// Дробный формат %5.3f - %: спецификатор, 5:минимальная ширина всего числа, .3: ширина дробной части, f: тип формата
|
||||
fmt.Printf("%%7.1f: %7.1f\n", 12.34567)
|
||||
// В формате дробной части цифры не округляются, а просто отбрасываются
|
||||
}
|
||||
57
chapter3/func/func.go
Normal file
57
chapter3/func/func.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Обявление функции (первая строчка до фигурных скобок - сигнатура функции)
|
||||
// line и times - параметры функции
|
||||
func repeatLine(line string, times int) {
|
||||
for i := 0; i < times; i++ {
|
||||
fmt.Println(line)
|
||||
}
|
||||
}
|
||||
|
||||
func paintNeeded(width float64, height float64) (float64, error) {
|
||||
if width < 0 {
|
||||
return 0, fmt.Errorf("A width of %.2f is invalid", width)
|
||||
}
|
||||
if height < 0 {
|
||||
return 0, fmt.Errorf("A height of %.2f is invalid", height)
|
||||
}
|
||||
area := width * height
|
||||
return area / 10.0, nil
|
||||
}
|
||||
|
||||
// Функция возвращающая значение (тип возврата - второй float64) и обязательно return
|
||||
func double(num float64) float64 {
|
||||
return num * 2
|
||||
}
|
||||
|
||||
// Множественный возврат из функци
|
||||
func manyReturns() (int, bool, string) {
|
||||
return 1, true, "hello"
|
||||
}
|
||||
|
||||
func main() {
|
||||
|
||||
// Вызов функции( параметры становятся аргументами функции)
|
||||
repeatLine("hello", 4)
|
||||
|
||||
// paintNeeded(4.2, 3.0)
|
||||
// paintNeeded(5.2, 3.5)
|
||||
// paintNeeded(5.0, 3.3)
|
||||
amount, err := paintNeeded(4.2, -3.0)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
/* log.Fatal(err) */
|
||||
} else {
|
||||
fmt.Printf("%.2f liters needed\n", amount)
|
||||
}
|
||||
|
||||
result := double(6.4) // Присвоение значения возврату из функции
|
||||
fmt.Print(result, "\n")
|
||||
|
||||
myNum, myBool, myString := manyReturns()
|
||||
fmt.Printf("Num: %d, Bool: %t, String: %s\n", myNum, myBool, myString)
|
||||
}
|
||||
18
chapter4/const/const.go
Normal file
18
chapter4/const/const.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
// объявление константы с типом
|
||||
const TriangleSides int = 3
|
||||
|
||||
// объявление константы без типа
|
||||
const SquareSides = 4
|
||||
|
||||
/* константам переназначить значение невозможно
|
||||
const PentagonSides = 5
|
||||
PentagonSides = 6 // error
|
||||
*/
|
||||
|
||||
func main() {
|
||||
fmt.Println(TriangleSides, SquareSides)
|
||||
}
|
||||
11
chapter4/const/dates/dates.go
Normal file
11
chapter4/const/dates/dates.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package dates
|
||||
|
||||
const DaysInWeek = 7
|
||||
|
||||
func WeeksToDays(weeks int) int {
|
||||
return weeks * DaysInWeek
|
||||
}
|
||||
|
||||
func DaysToWeek(days int) float64 {
|
||||
return float64(days) / float64(DaysInWeek)
|
||||
}
|
||||
12
chapter4/const/planner/main.go
Normal file
12
chapter4/const/planner/main.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang-book/head-first-go/chapter4/const/dates"
|
||||
)
|
||||
|
||||
func main() {
|
||||
days := 3
|
||||
fmt.Println("Your appointment is", days, "days")
|
||||
fmt.Println("with a follow-up in", days+dates.DaysInWeek, "days")
|
||||
}
|
||||
11
chapter4/greeting/greeting.go
Normal file
11
chapter4/greeting/greeting.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package greeting
|
||||
|
||||
import "fmt"
|
||||
|
||||
func Hello() {
|
||||
fmt.Println("Hello!")
|
||||
}
|
||||
|
||||
func Hi() {
|
||||
fmt.Println("Hi!")
|
||||
}
|
||||
14
chapter4/hi/main.go
Normal file
14
chapter4/hi/main.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang-book/head-first-go/chapter4/greeting"
|
||||
)
|
||||
|
||||
func main() {
|
||||
greeting.Hello()
|
||||
greeting.Hi()
|
||||
|
||||
slc := []string{"hello", "world"}
|
||||
fmt.Printf("%s %T %T", slc[0], slc, true)
|
||||
}
|
||||
23
chapter4/keyboard/keyboard.go
Normal file
23
chapter4/keyboard/keyboard.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package keyboard
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func GetFloat() (float64, error) {
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
input, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
input = strings.TrimSpace(input)
|
||||
number, err := strconv.ParseFloat(input, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return number, nil
|
||||
}
|
||||
23
chapter4/passfail/pass_fail.go
Normal file
23
chapter4/passfail/pass_fail.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang-book/head-first-go/chapter4/keyboard"
|
||||
"log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Print("Enter a grade: ")
|
||||
grade, err := keyboard.GetFloat()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var status string
|
||||
if grade >= 60 {
|
||||
status = "passing"
|
||||
} else {
|
||||
status = "failing"
|
||||
}
|
||||
fmt.Println("A grade of", grade, "is", status)
|
||||
}
|
||||
17
chapter4/tocelsius/tocelsius.go
Normal file
17
chapter4/tocelsius/tocelsius.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"golang-book/head-first-go/chapter4/keyboard"
|
||||
"log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Print("Enter a temperature in Farenheit: ")
|
||||
farenheit, err := keyboard.GetFloat()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
celsius := (farenheit - 32) * 5 / 9
|
||||
fmt.Printf("%0.2f degrees Celsius\n", celsius)
|
||||
}
|
||||
Reference in New Issue
Block a user