How can I write from multiple writers in golang?

huangapple go评论86阅读模式
英文:

How can I write from multiple writers in golang?

问题

创建一个函数,该函数将数据写入多个写入器,并返回每个写入器写入的字节数,返回的字节数的索引位置对应于写入器的索引位置。如果切片为空,则返回空切片([]int{})。

错误函数:

type Errors []error

func (m Errors) Error() string {
    count := 0
    for t := 0; t < len(m); t++ {
        if m[t] != nil {
            count += 1
        }
    }
    errindex := 0
    for t := 0; t < len(m); t++ {
        if m[t] != nil {
            errindex = t
            break
        }
    }

    if count == 0 {
        return fmt.Sprintf("(0 errors)")
    } else {
        if count == 1 {
            return fmt.Sprintf("%v", m[errindex])
        } else if count == 2 {
            return fmt.Sprintf("%v (and 1 other error)", m[errindex])
        } else {
            return fmt.Sprintf("%v (and %d other errors)", m[errindex], count-1)
        }
    }
}

你的新代码:

func WriteTo(b []byte, writers ...io.Writer) (n []int, errs errors.Errors) {
    if len(writers) == 0 {
        return []int{}, nil
    }
    for i := 0; i < len(writers); i++ {
        num, err := writers[i].Write(b) // 将字节写入当前写入器
        n = append(n, num)              // 添加当前写入器写入的字节数
        if err != nil {
            switch err {
            case io.ErrShortWrite:
                errs = append(errs, err)
            default:
                errs = append(errs, err)
            }
        }
    }
    return n, errs
}

你尝试修复代码,但有些测试未通过。你无法看出问题所在。当count == 1时,返回的是count == 0的情况,当count == 2时,返回的是count == 0的情况。

[]error{nil, io.ErrShortWrite, nil},

[]error{nil, io.ErrShortWrite, io.ErrShortWrite},

以上是测试用例。

英文:

The idea is to create a function that will write to several writers and do a return so that:

  • write the []byte slice to all writers
  • return n bytes written by each writer with index position corresponding to the index position of the writer.
    -if slice is empty return ([]int{})
    ... etc

Error function:

type Errors []error


func (m Errors) Error() string {
	count := 0
	for t := 0; t &lt; len(m); t++ {
		if m[t] != nil {
			count += 1

		}
	}
	errindex := 0
	for t := 0; t &lt; len(m); t++ {
		if m[t] != nil {
			errindex = t
			break
		}
	}

	if count == 0 {
		return fmt.Sprintf(&quot;(0 errors)&quot;)
	} else {
		if count == 1 {
			return fmt.Sprintf(&quot;%v&quot;, m[errindex])
		} else if count == 2 {
			return fmt.Sprintf(&quot;%v (and 1 other error)&quot;, m[errindex])
		} else {
			return fmt.Sprintf(&quot;%v (and %d other errors)&quot;, m[errindex], count-1)

		}

	}
}

My new code:

func WriteTo(b []byte, writers ...io.Writer) (n []int, errs errors.Errors) {
	if len(writers) == 0 {
		return []int{}, nil
	}
	for i := 0; i &lt; len(writers); i++ {
		num, err := writers[i].Write(b) // write bytes to a current writer
		n = append(n, num)              // add bytes written by current write
		if err!=nil{
			switch err{
			case io.ErrShortWrite:
				errs = append(errs, err)
			default:
				errs = append(errs, err)
			}
		}
	}
	return n, errs
}

I try to fix it but some tests don't pass. Can't really see the problem. Instead of returning when count == 1, returns when count == 0 and when count == 2, return as for count == 0

	[]error{nil, io.ErrShortWrite, nil},

	[]error{nil, io.ErrShortWrite, io.ErrShortWrite},

答案1

得分: 4

你可以使用io.MultiWriter()函数,它接受任意数量的io.Writer并返回一个单一的io.Writer,该写入器将数据复制到所有提供的写入器中。

例如:

buf1 := &bytes.Buffer{}
buf2 := &bytes.Buffer{}

w := io.MultiWriter(buf1, buf2)

if _, err := w.Write([]byte("Hello")); err != nil {
	panic(err)
}

fmt.Println("Buf1:", buf1.String())
fmt.Println("Buf2:", buf2.String())

这将输出(在Go Playground上尝试):

Buf1: Hello
Buf2: Hello
英文:

You may use io.MultiWriter() which takes arbitrary number of io.Writers and returns a single io.Writer, which duplicates writes to all provided writers.

For example:

buf1 := &amp;bytes.Buffer{}
buf2 := &amp;bytes.Buffer{}

w := io.MultiWriter(buf1, buf2)

if _, err := w.Write([]byte(&quot;Hello&quot;)); err != nil {
	panic(err)
}

fmt.Println(&quot;Buf1:&quot;, buf1.String())
fmt.Println(&quot;Buf2:&quot;, buf2.String())

This will output (try it on the Go Playground):

Buf1: Hello
Buf2: Hello

huangapple
  • 本文由 发表于 2021年9月18日 17:13:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/69233257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定