Как вернуть промежуточное значение?
Как вернуть status = 2, не прерывая цикл [и функцию]?
package main
import (
"fmt"
"math/rand"
"time"
)
// Значения status: 1 - "успешно"; 2 - "неудачно впервые"; 3 = "неудачны все попытки".
func SendMail() (status int) {
for i := 1; i < 6; i++ { // максимальное количество попыток.
isSuccess := rand.Intn(2) == 1 // случайное число true/false для теста
if isSuccess {
fmt.Println("Успешно! i =", i)
return 1
}
if !isSuccess && i == 1 {
fmt.Println("Неуспешно впервые. i =", i)
status = 2
}
time.Sleep(2 * time.Second)
}
status = 3
fmt.Println("Неудачны все попытки. i = 5")
return
}
func main() {
rand.Seed(time.Now().UnixNano())
var my_status = SendMail()
if my_status == 1 {
fmt.Println("main: Успешно!")
}
if my_status == 2 {
fmt.Println("main: Неуспешно впервые.")
}
if my_status == 3 {
fmt.Println("main: Неудачны все попытки.")
}
}
https://go.dev/play/p/X44qX3w4VYm
Ответы (1 шт):
Автор решения: Maksim Fedorov
→ Ссылка
Как подсказали — пишите в канал. Вот работающий переделанный ваш пример https://go.dev/play/p/-olSoQuWLuV
P.S: Ну и число попыток снаружи можно передать
package main
import (
"fmt"
"math/rand"
"time"
)
type SendAttempt struct {
status int
first bool
}
func main() {
rand.Seed(time.Now().UnixNano())
attempts := make(chan SendAttempt)
go SendMail(attempts)
for {
select {
case atm, ok := <-attempts:
if !ok {
fmt.Println("Исчерпаны все попытки")
return
}
if atm.status == 1 {
fmt.Println("Успешно!")
return
}
if atm.status == 2 {
msg := ""
msg = msg + "Неуспешно"
if atm.first {
msg = msg + " впервые"
}
fmt.Println(msg)
continue
}
if atm.status == 3 {
fmt.Println("main: Неудачны все попытки.")
continue
}
default:
continue
}
}
}
// Значения status: 1 - "успешно"; 2 - "неудачно впервые"; 3 = "неудачны все попытки".
func SendMail(attempts chan<- SendAttempt) {
for i := 1; i < 6; i++ {
isSuccess := rand.Intn(2) == 1
if isSuccess {
attempts <- SendAttempt{1, false}
continue
}
if !isSuccess {
attempts <- SendAttempt{2, i == 1}
continue
}
time.Sleep(2 * time.Second)
}
attempts <- SendAttempt{3, false}
close(attempts)
}