Compare two slices of strings

polaris · 2015-03-29 09:18:58 · 1188 次点击    
这是一个分享于 2015-03-29 09:18:58 的资源,其中的信息可能已经有所发展或是发生改变。

I'm able to get a list of files and folders from a directory, I've written a function called isDir to return True if the path is a directory.

Now my problem is that I want to make sure that none of the folders listed match a list of strings in a slice. The code I have might skip the first match but it will print out everything else anyways. I need to process the folders that aren't to be avoided.

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

func isDir(pth string) (bool) {
         fi, err := os.Stat(pth)
         if err != nil {
                 return false
         }
         return fi.Mode().IsDir()
}

func main() {
    gcomputer := "localhost"
    location := fmt.Sprintf("\\\\%s\\c$\\Users\\", gcomputer)
    // Profiles to avoid
    avoid := []string{"Administrator", "Default", "Public"}
    // walk through files & folders in the directory (location) & return valid profiles
    files, _ := ioutil.ReadDir(location)
    for _, f := range files {
        fdir := []string{location, f.Name()}
        dpath := strings.Join(fdir, "")

        if isDir(dpath) {
            for _, iavoid := range avoid {
                for iavoid != f.Name() {
                    fmt.Println(dpath)
                    break
                }
                break
            }
        }
    }
}

I don't mind using a third-party module, I've been working on this too long and starting to lose my cool, making understanding the docs a bit difficult. Any tips would be appreciated.


评论:

CodeAddict:

Well peterSO solved this for me at StackOverflow.

dchapes:

With a name of "CodeAddict" you can't solve a trivial, basic, programming 101, if-you-can't-do-this-you-can't-program problem so you get someone else to do it for it?? IMO any such trivial "questions" should be deleted from SO else it becomes a giant rephrasing of the basic manuals/specs and explanations of how to write a fucking loop.

printf_hello_world:

For a beginner programmer, the connection between their problem and a "fucking loop" may not be immediately obvious. SO helps make that relationship clear.

Everyone starts from somewhere; perhaps we should encourage CodeAddict's enthusiasm rather than squash it from atop our pedestals.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1188 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传