var count int
var listcount [ ] int
by declaring
The following replaceFileContents
function contains an increment of
count++
listcount=append(listcount, count)
I wrote and executed .
fmt.Println("Total files replaced are"+len(listcount))
displays 0
.Isn't the price delivered well?There are no errors, but it's hard to tell where the problem is.
func replaceFileContents(path string, before, after[]byte, count int, listcount[]int) error {
read,err: =ioutil.ReadFile(path)
if bytes.Contains(read, before) {
newContents: = bytes.Replace(read, before, after, -1)
err=ioutil.WriteFile(path, newContents, os.ModePerm)
if err!=nil{
return err
}
}
fmt.Println("Replaced File:"+path)
count++
listcount=append(listcount, count)
return nil
}
funcmain(){
var count int
var listcount [ ] int
root: = input ("file path")
before: = [ ] byte (input("pre-replacement string")
after: = [ ] byte (input("replaceable string")
error: = filepath.Walk(root, func(path string, fios.FileInfo, error) error {
if err!=nil{
return err
}
matched,err: = filepath.Match("*log.xml", fi.Name())
if err!=nil{
panic(err)
}
if fi.IsDir()|! matched {
// if fi.IsDir()||filepath.Ext(fi.Name())!=".xml"{
return nil
}
return replaceFileContents (path, before, after, count, listcount)
})
if err!=nil{
panic(err)
}
fmt.Println("Total files replaced are"+len(listcount))
}
Lack of understanding of Go price/pointer (see ) delivery
Try the simple comparison code below to see the difference.
package main
import "fmt"
funcaddToList1(list[]int, xint){
list=append(list,x)
}
funcaddToList2(list*[]int, xint){
*list=append(*list,x)
}
funcmain(){
{
var list1 [ ] int
for i —=0; i<10;i++{
addToList1(list1,i)
}
fmt.Printf("Count=%d\n", len(list1)")
}
{
var list2 [ ] int
for i —=0; i<10;i++{
addToList2 (&list2,i)
}
fmt.Printf("Count=%d\n", len(list2))"
}
}
The addToList1()
function is a value pass, so the provisional argument list
is a copy of list1
in the main()
function in the call example above.
A temporary argument is a type of local variable, and changes to the temporary argument do not affect the real argument and are discarded when it leaves the function.
Because the addToList2()
function is pointer passed, the provisional argument list
holds the address of list2
in the main()
function in the call example above.
By referencing the pointer with the *
operator, you can obtain references to the entity and read and rewrite objects.
Large data structures such as arrays are expensive to copy every time, so even if they are just read, they are basically pointer-delivered.
© 2024 OneMinuteCode. All rights reserved.